1

I'm not into JavaScript OOP, so I've made an object with some fields which contains some functions to invoke.

var test = {
    questions: [],

    addQuestion: function(questionTitle, possibleAnwsers)
    {
        // not really important
    },

    appendQuestionToHTML: function(question)
    {
        // not really important
    },

    makeQuestionFieldsEditable: function($questionNode)
    {
        $questionNode.find(".questionTitle").first(function(){this.changeTextOnClick($(this));});
        $questionNode.find(".questionChoice").each(function(){this.changeTextOnClick($(this));});
    },

    changeTextOnClick: function($spanElement)
    {
        // not really important
    }
};

Following object in makeQuestionFieldsEditable() function looks for ".questionTitle"-class node and all of ".questionChoice"-class nodes invoke another function for them. The problem is that using this in anonymous function references to itself, not function saved on field changeTextOnClick. Javascript/JQuery wants to invoke this function on HTMLDivElement, which doesn't exists.

Is there any solution?

2 Answers 2

3

You can do the trick using a reference to your this variable :

makeQuestionFieldsEditable: function($questionNode)
{
    var that = this;
    $questionNode.find(".questionTitle").first(function(){that.changeTextOnClick($(this));});
    $questionNode.find(".questionChoice").each(function(){that.changeTextOnClick($(this));});
},
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, it's too simple, I cannot accept your anwser. Just kidding, thanks.
1

I think all you need to do is change 'this' to 'test' (the variable you have assigned this object to).

4 Comments

an object should never have to refer to itself by the name of a variable referencing it.
This one also works, but I don't think if it's right way. Thanks anyway.
@Visher it works, but it's a nasty hack. If test gets renamed then the contents of the object have to change too. It also prevents more than one instance of the object from existing.
I object to the phrase "nasty hack" in reference to calling a singleton by its name. If it were declared as a class rather than a singleton, that's another story.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.