简体   繁体   中英

A simple event system | How to?

I want to implement this interface

addListener(name, callback);
removeListener(name, [callback]); // callback is optional
trigger(name);

All events will be triggered on an internal event bus

var bus = {}

that is not part of the interface.

This is the simplest interface I could imagine that is actually useful.

However I still don't how to implement these interfaces conceptually. I've perused the backbone event system , but can't quite understand how they implement this core functionality.

I just want to write a quick 10-100 line event system that is as simple as possible and based upon the more complex Backbone event system.

You could use Backbone.Events module for it.

Stolen shamelessly from lostechies

You could use an Application level event aggregator:

MyApp = {};
MyApp.vent = _.extend({}, Backbone.Events);

MyApp.vent.on("some:event", function(){
  alert("some event was fired!");
});

MyApp.vent.trigger("some:event");

Check out the minimal event bus library minibus.js . It currently has different API but might be exactly what you are looking for.

var bus = Minibus.create();
bus.on(name, callback);  // add listener
bus.emit(name);          // trigger event
bus.off(name);           // remove listener

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM