从 'initialize' 中的函数引用 Prototype.js 函数
Referencing a Prototype.js function from a function inside 'initialize'
在下面的 JavaScript 代码中,我如何从 function(elem) {...
内部引用 reachMe
函数?我只是想将一个侦听器附加到 elem
,以便在 elem
被点击时调用 reachMe
。
如果我用 this
替换 whatHereToMeanTheReachMeFunction
它不起作用,因为 this
是 window
对象。相反,如果我把 reachMe
放在那里,我会得到错误 Uncaught TypeError: Cannot read 属性 'bindAsEventListener' of undefined.
var MyClass = Class.create();
MyClass.prototype = {
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
elem.observe('click', whatHereToMeanTheReachMeFunction.bindAsEventListener(this));
}
);
},
reachMe : function(event) {
console.log("Here I am.");
}
}
我对您的代码做了一些调整,希望这对您有所帮助
var MyClass = Class.create({
//The class can be defined in one fell swoop
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
//you should only need normal bind() here
elem.observe('click',this.reachMe.bind(this));
},this
//include 'this' here to set the context inside the each method
);
//you could also do the above action like this, 1 observer vs multiple
document.on('click','*[id^=prefix]',this.reachMe.bind(this));
},
reachMe : function(event) {
console.log("Here I am.");
}
}
在下面的 JavaScript 代码中,我如何从 function(elem) {...
内部引用 reachMe
函数?我只是想将一个侦听器附加到 elem
,以便在 elem
被点击时调用 reachMe
。
如果我用 this
替换 whatHereToMeanTheReachMeFunction
它不起作用,因为 this
是 window
对象。相反,如果我把 reachMe
放在那里,我会得到错误 Uncaught TypeError: Cannot read 属性 'bindAsEventListener' of undefined.
var MyClass = Class.create();
MyClass.prototype = {
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
elem.observe('click', whatHereToMeanTheReachMeFunction.bindAsEventListener(this));
}
);
},
reachMe : function(event) {
console.log("Here I am.");
}
}
我对您的代码做了一些调整,希望这对您有所帮助
var MyClass = Class.create({
//The class can be defined in one fell swoop
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
//you should only need normal bind() here
elem.observe('click',this.reachMe.bind(this));
},this
//include 'this' here to set the context inside the each method
);
//you could also do the above action like this, 1 observer vs multiple
document.on('click','*[id^=prefix]',this.reachMe.bind(this));
},
reachMe : function(event) {
console.log("Here I am.");
}
}