You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Observable is a JavaScript mixin for adding observer methods to a function. It's similiar to the jQuery event system, but can be added into any other module. You can use it for your own JavaScript libraries.
Usage
npm install observable_js or copy the source from lib/observable.js.
Observable will be assigned to the global scope if you don't use node and no other AMD or CommonJS loader is present.
ES6:
classMyLibraryextendsObservable{}
CoffeeScript:
classMyLibraryextendsObservable
(Don't forget to call super if your extended ES6/CoffeeScript class has its own constructor function.)
Other usages:
// Adding the Observable methods to an existing object:Observable.mixin(a)// Add the methods to the prototype of a constructor functionObservable.mixin(Constructor.prototype)// Create a new object that has all the Observable methodsvara=newObservable()
Features
Super easy to use for your library, just extend from it or mixin the methods
Most methods are overloaded, making the API very nice to use
All methods are chainable
It's very well tested
Node / NPM and the browser are both supported
Documentation
The object that gains the observable methods will be called x in this README for convenience.
on: subscribing to events
You can watch a single event:
x.on('topic',fn);
You can also watch several events at once:
x.on(['topic1','topic2'],fn);
Or watch several events at once that need different handlers:
x.on({topic1: fn,topic2: fn2});
once
The once method behaves exactly like on and accepts the same arguments, but after triggering the event for the first time the event will be removed.
x.once('topic',fn);x.trigger('topic');// fn will be triggeredx.trigger('topic');// fn won't be triggered, event doesn't exist anymore
trigger: firing events
Calling .trigger('topic') will execute all function subscribed to 'topic'.
You can also pass arguments to the subscribed functions by passing an array as the second argument:
x.on('topic',function(arg1,arg2){console.log(arg1,arg2);});x.trigger('topic',[[1,2],true]);// Logs [1, 2] and true
off: unsubscribing from events
This method accepts the exact same arguments as on and once. You pass the
topic and the functions you want to unsubscribe. Observable will only remove the
passed function from the topic.