我想在插件内部和外部调用我的插件上的单击事件。我的意思是如果我添加:
clicked: function() { console.log("called from outside"); },
作为插件实例的选项,插件将执行自己的函数,然后从选项中调用自定义函数。这是代码:
(function() {
// Define our constructor
this.Test = function() {
this.options = arguments[0];
}
Test.prototype.make = function(){
this.SelectArea = document.getElementById(this.options.id);
this.SelectArea.addEventListener('click', function(){
// first execute scripts to this function
console.log("calling from inside");
// then execute options clicked function
this.options.clicked;
});
}
}());
var Test = new Test({
id: 'testId',
clicked: function(){
console.log("calling from outside");
}
});
Test.make();
但是上面的代码失败了,它只触发一次。选项中的 clicked
事件函数未执行。
最佳答案
this.options.clicked;
您在这里根本没有调用该函数,您只是引用它。您需要添加括号来调用它:
this.options.clicked();
但是还有另一个问题。在点击事件回调中,this
是 DOM 元素,而不是 Test
实例。您需要保存对它的引用,并这样调用它:
Test.prototype.make = function(){
this.SelectArea = document.getElementById(this.options.id);
var clickHandler = this.options.clicked;
this.SelectArea.addEventListener('click', function(){
// first execute scripts to this function
console.log("calling from inside");
// then execute options clicked function
clickHandler(); // here
});
}
并且,为了更好,您可能需要传递事件变量和 DOM 上下文,以防处理程序想要使用它:
clickHandler.apply(this, arguments);
关于javascript - 如何将事件两次绑定(bind)到 JavaScript 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27806846/