[英]How do I subscribe to a method in jQuery?
我想做这样的事情。
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()中触发一个自定义事件:
this.run = function() {
// Trigger an event called "run"
$(this).triggerHandler('run');
// ...
};
现在,您可以按照已经完成的方式订阅此活动:
var f = new foo();
$(f).on('run', function() { ... }); // "bind" is fine as well
这将对绑定处理程序之后触发的事件起作用,因此构造函数中触发的事件很可能不会被捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.