Hello,
I'm trying to use the Class methods of prototype.js to manage my object hierarchy on my current project, but I have some trouble with the this keyword in conjonction with Class.create.
Here is a piece of old-fashioned plain js code to create inheritance:
var Super1 = function () {
this.fu = "bar";
}
var Sub1 = function () {
this.baz = "bat";
this.f = function (e) {
alert("Sub1:"+this.fu+this.baz);
}.bindAsEventListener(this);
document.observe("click", this.f);
};
Sub1.prototype = new Super1();
new Sub1();
And here is my first attempt at mimicking this with Class.create:
var Super2 = Class.create({
fu: "bar"
});
var Sub2 = Class.create(Super2, {
baz: "bat",
f: function (e) {
alert("Sub2:"+this.fu+this.baz);
}.bindAsEventListener(this),
initialize: function () {
document.observe("click", this.f);
}
});
new Sub2();
So far so good... But of course it doesn't work: f is bound to window, not to the object created with new. The only way I found is:
var Super3 = Class.create({
fu: "bar"
});
var Sub3 = Class.create(Super3, {
baz: "bat",
f: function (e) {
alert("Sub3:"+this.fu+this.baz);
},
initialize: function () {
this.f = this.f.bindAsEventListener(this);
document.observe("click", this.f);
}
});
new Sub3();
But it's really inelegant. How am I supposed to handle this?
edit (to reply to Colin):
I need to bind f itself, so that I can call stopObserving on f (see http://prototypejs.org/api/event/stopObserving)
I still need bindAsEventListener every time I need this inside the listener, since by default this is the element that fires the event (see http://prototypejs.org/api/event/observe)
I'm still waiting for an anwser on the googlegroup :) I kind of posted here to see whether I can get a faster answer via S.O.
I could (and probably should) use bind instead of bindAsEventListener. I used the latter to make it clear that I'm getting a listener. It doesn't change the fact that the binding procedure is inelegant.