javascript - 如何将事件两次绑定(bind)到 JavaScript 插件

标签 javascript dom-events

我想在插件内部和外部调用我的插件上的单击事件。我的意思是如果我添加:

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/

相关文章:

javascript - Firefox 中的默认事件对象?

javascript - react-intl - FormattedDate - DD/MM/YYYY 而不是 MM/DD/YYYY(对于 en-us!)

javascript - 在 FireFox/Greasemonkey 中使用 JavaScript 发送全局击键

Javascript - 添加时触发事件

javascript - 清除每个事件处理程序

javascript - 触发选择标签以显示选项

javascript - 从 .load() jquery 函数中省略 Google map

javascript - 一堆小闭包 vs 一个大闭包

javascript - 我尝试通过数据库验证数据以使用 Bootstrap 模式和 ajax 与 PHP 登录,但它不起作用

javascript - 如何使用 Zurb Foundation 显示打开、打开、关闭、关闭回调函数?