我有一个 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
您需要在点击函数中维护
this
引用。我使用了$.proxy
;有些人使用var self = this;
Toolbar
不是 jQuery 对象,因此应将其包装在$()
中以访问 jQuery 的函数。还将引用Toolbar
实例的this
包装在点击函数中。
关于javascript - Javascript 文字对象可以触发事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8365037/