If setOnclick
is implemented nicely, you should probably be able to do:
bt.setOnclick(function() {
alert(this.name + " clicks = " + this.cntClick);
this.onclick = this.cntClick + 1;
});
Otherwise, you need to create a new scope for each callback function so that they each have their own bt
. One way to do that would be:
bt.setOnclick(function(bt){
return function(){
alert(bt.name + " clicks = " + bt.cntClick);
bt.onclick = bt.cntClick + 1;
};
}(bt));
Comment Response
To implement setOnClick such that this
refers to the relevant HrButton
(rather than the element
) within the callback, you can use the following code (works in modern browsers only, unless you SHIM bind):
var self = this;
self.setOnClick = function(fnOnClick) {
element.onclick = fnOnClick.bind(self);
};
Since you're using jQuery the following code will be a cross-browser equivalent:
var self = this;
self.setOnClick = function(fnOnClick) {
element.onclick = $.proxy(fnOnClick, self);
};
Otherwise this will work in all browsers, without any libraries, and is only slightly less readable:
var self = this;
self.setOnClick = function(fnOnClick) {
element.onclick = function(event) {
return fnOnClick.call(self, event);
};
};