I’m trying to use Mootools to add a button to a page dynamically. It all works fine, except the addEvent in the addButton function. I get an error saying that “Property ‘sayHi’ of object javascript:void(0); is not a function”.
I assume this is due to my scope and that I somehow must bind the addButton function back to the global “this”? Can someone explain what I’m doing wrong? Thanks!
var myClass = new Class({
initialize: function(){
this.sayHi();
},
sayHi: function(){
alert('Hello World!');
},
addButton: function(){
this.hiButton = new Element('a', {
id: 'sayhi',
html: 'Hi!',
href: 'javascript:void(0);',
events: {
click: function(){
this.sayHi();
}
}
}).inject($('myDiv'));
}
});
The problem is that in your click handler, the
thisvalue is no longer the original object, but rather the button that was clicked on.There might be a MooTools-specific way to address this, but wrapping this object creation in a function would be a simple, native way to solve this:
And then
EDIT
While the above is a fairly standard idiom in JavaScript, I’m told it doesn’t play well with MooTools. If that’s the case, I would go with this (as another answer already mentions):