javascript - Javascript 文字对象可以触发事件吗?

标签 javascript jquery events object-literal

我有一个 Javascript 对象字面量:

var Toolbar = {

    init: function(toolbar) {
        this.Bar = $(toolbar); // scope is Toolbar object literal

        this.Bar.find('clearButton').click(function() {
            this.trigger('clear'); // doesn't work!
            this.Bar.trigger('clear'); // works!
    }
}

Toolbar.init($('div.toolbar'));
Toolbar.bind('clear', function() { ... }); // doesn't work!
Toolbar.Bar.bind('clear', function() { ... }); // works!

我希望能够在 Toolbar 对象字面量而不是字面量中引用的工具栏 DOM 对象上触发 clear 事件。这可能吗?如果可能,我该怎么做?

最佳答案

这应该有效:

var Toolbar = {

    init: function(toolbar) {
        this.Bar = $(toolbar); // scope is Toolbar object literal

        this.Bar.find('.clearButton').click($.proxy(function() {
            $(this).trigger('clear'); // should work now
            this.Bar.trigger('clear'); // still works
        }, this));
    }
};

Toolbar.init($('div.toolbar'));

$(Toolbar).bind('clear', function() { 
    console.log('Toolbar'); 
}); // should work now

Toolbar.Bar.bind('clear', function() { 
    console.log('Toolbar.Bar'); 
}); // still works
  1. 您需要在点击函数中维护this 引用。我使用了 $.proxy;有些人使用 var self = this;

  2. Toolbar 不是 jQuery 对象,因此应将其包装在 $() 中以访问 jQuery 的函数。还将引用 Toolbar 实例的 this 包装在点击函数中。

关于javascript - Javascript 文字对象可以触发事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8365037/

相关文章:

javascript - 按下按钮时更改 li 元素类,并在该 css 类中更改背景颜色

javascript - Uncaught Error : cannot call methods on dialog prior to initialization using jQuery

javascript - JQuery 中的可插入编辑组件

C#: Action 委托(delegate)与显式委托(delegate)

c# - WebControl 和 CompositeControl 之间的区别?

javascript - Backbone.js:读取json文件

javascript - React.js 中的纺车

javascript - 具有不同逻辑的类似 React 组件

javascript - jquery get() url作为变量的解决方法

java - 为什么异常处理不能处理异步事件?