I would like to use fnB in click handler. Is there any elegant solution? Thanks.
A = function() {
...
}
B = function() {
...
}
B.prototype = new A();
B.prototype.fnB = function() {}
B.prototype.fn = function() {
// this isntanceof B -> true
jQuery(selector).click(function() {
this.fnB() // this instance of B -> false, this == $(selector) -> true
}
}
Implementation based on SoWeLie’s answer:
EventType = {
ButtonClicked: 0
...
}
function Delegate(object, method) {
return function() { method.apply(object, arguments); }
}
function Observable() {
this._eventHandlers = {};
}
Observable.prototype = {
addListener: function(eventType, listener) {
if(!this._eventHandlers.eventType) {
this._eventHandlers.eventType = [];
}
this._eventHandlers.eventType.push(listener);
},
removeListener: function(eventType, listener) {
if(this._eventHandlers.eventType) {
for(var i = this._eventHandlers.eventType.length; --i > -1;) {
if(!listener || this._eventHandlers.eventType[i] == listener) {
this._eventHandlers.eventType.splice(i, 1);
}
}
}
},
fireEvent: function(eventType, data) {
if(this._eventHandlers.eventType) {
for(var i = 0; i < this._eventHandlers.eventType.length; ++i) {
var handleEvent = this._eventHandlers.eventType[i];
if(handleEvent) {
handleEvent(this, data);
}
}
}
}
}
Dialog.Buttons = { ButtonOk: 0, ButtonCancel: 1, ButtonYes: 2, ButtonNo: 3, ButtonClose: 4 };
Dialog.prototype = new Observable();
Dialog.prototype.bindEvents = function() {
$('#dlgButtonOk', this._$el).click(Delegate(this, function() {
this.fireEvent(EventType.ButtonClicked, Dialog.Buttons.ButtonOk );
}));
$('#dlgButtonCancel', this._$el).click(this, function() {
this.fireEvent(EventType.ButtonClicked, Dialog.Buttons.ButtonCancel );
});
$(function() {
dialog = new Dialog('.dialogWnd')
dialog.addListener(EventType.ButtonClicked, function() {alert(1)})
});
????
Oops! Your edit couldn’t be submitted because:
Your post does not have much context to explain the code sections; please explain your scenario more clearly.
???
The most elegant solution is to use the apply method of a function:
Change your code like so:
Notice the call to hitch on your anonymous function, this will ensure the cope is preserved within the click handler.