I have an object in JavaScript. I suppose it looks like:
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 the object setup in Javascript, and when it loads, it creates an anchor tag. This anchor tag in the form of a background image in CSS (hence it is not empty).
Now, I understand that the 'this' statement, when the button will actually be clicked, instead of the MyButton element that I have created.
I have tried to use call (), try () and bind () and I can not get it to do this work. I need that when the button is clicked, So it goes back to the realm of the object and not the html element's scope.
What am I missing here?
Click this value
inside the event handler refers to the DOM element , Not the object instance of your constructor.
You need to continue with that value, you also see MyButton.onButtonClick
that you can change the onButtonClick
method to MyObject.prototype Want to declare
:
MyObject.prototype.load = function () {var instance = this; // .. this.MyButton.click (function (e) {// & lt; - It looks like you are using jQuery / `` ``` `` `` `` `` `` / / ...};
Comments
Post a Comment