I wrote following code to implement simple 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
. 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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.