在jQuery中,您可以使用这样的回调:
$('#btn').on('click', function() {
// code
});
我怎么能写出像
foo.on('bar', function() {
// code
});
foo.on('buzz', function() {
//code
});
?
谢谢.
解决方法:
像那样:
var eventBus = function () {
var supportedEvents = ['bar', 'buzz'];
var subscribers = {};
for (var i = 0; i < supportedEvents.length; i++) {
subscribers[supportedEvents[i]] = [];
}
return {
on: function (event, action) {
subscribers[event].push(action);
},
trigger: function (event) {
var funsToCall = subscribers[event] || []; // empty array if unsupported event
for (var i = 0; i < funsToCall.length; i++) {
funsToCall[i](); // calling a function
}
}
}
}
然后你调用eventBus函数来获取一个将成为你的foo的对象:
var foo = eventBus();
foo.on('bar', function () {
console.log('bar');
});
foo.on('buzz', function () {
console.log('buzz');
});
foo.trigger('bar'); // prints 'bar' to the console
foo.trigger('buzz'); // prints 'buzz' to the console