我想做这样的事情.
var foo = function() {
this.run = function() {
alert('got');
}
this.init = function() {
this.run();
}
this.init();
};
window.onload = function() {
var f = new foo();
$(f).bind('run', function() { // this doesn't work
alert('ran!');
});
};?
Run Code Online (Sandbox Code Playgroud)
它不起作用.我如何订阅另一个对象的方法?
您无法将事件处理程序直接绑定到函数 - 您将它们绑定到事件!您需要在run()中触发自定义事件:
this.run = function() {
// Trigger an event called "run"
$(this).triggerHandler('run');
// ...
};
Run Code Online (Sandbox Code Playgroud)
现在您可以按照以下方式订阅此活动:
var f = new foo();
$(f).on('run', function() { ... }); // "bind" is fine as well
Run Code Online (Sandbox Code Playgroud)
这将适用于绑定处理程序后触发的事件,因此很可能不会捕获构造函数中触发的事件.