[英]pub/sub API does not work
I wrote following code to implement simple pub/sub API. 我编写了以下代码来实现简单的pub / sub API。
(function ($) {
var o = $({});
$.each({
trigger: 'trigger',
on: 'listen',
off: 'stopListen'
}, function (key, val) {
jQuery[val] = function () {
//console.log(o[key]);
o[key].apply(o, arguments);
}
});
})(jQuery);
$.trigger('watch');
$.listen('watch', function (e, data) {
alert('Watch it');
});
However, above code does not alert Watch it
. 但是,上面的代码不会提醒
Watch it
。 Why it does not work and how can I fix it? 为什么它不起作用,我该如何解决?
You have to listen to the event before you trigger it. 在触发事件之前,您必须先听取事件。 Try executing in this order:
尝试按此顺序执行:
$.listen('watch', function (e, data) {
alert('Watch it');
});
$.trigger('watch');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.