views:

13

answers:

1

I have an object I created in JavaScript. Let's say it looks like this:

function MyObject() {
    this.secretIdea = "My Secret Idea!";
};

MyObject.prototype.load = function() {
    this.MyButton = $(document.createElement("a"));
    this.MyButton.addClass("CoolButtonClass");
    this.MyButton.click = MyButton.onButtonClick;
    someRandomHtmlObject.append(this.MyButton);
};

MyObject.prototype.onButtonClick = function(e) {
    alert(this.secretIdea);
};

As you can see, I have an object setup in JavaScript and, when it's loaded, it creates an anchor tag. This anchor tag as a background image in CSS (so it's not empty).

Now, I understand that the 'this' statement, when the button would actually be clicked, would fall to the scope of the MyButton element rather than the object I have created.

I have tried using call(), try() and bind() and I cannot get this to work. I need it so that, when the button is clicked, it goes back to the object's scope and not the html element's scope.

What am I missing here?

+1  A: 

The this value inside the click event handler refers to the DOM element, not to the object instance of your constructor.

You need to persist that value, also you refer to MyButton.onButtonClick I think you want to refer the onButtonClick method declared on MyObject.prototype:

MyObject.prototype.load = function() {
    var instance = this;
    //..
    this.MyButton.click(function (e) { // <-- looks like you are using jQuery
      // here `this` refers to `MyButton`
      instance.onButtonClick(e);
    });
    //...
};
CMS
Oh I get it. This works perfectly!Awesome, thanks!
Kris