A JavaScript observer pattern mixin.
For an introduction to why you might want to use the observer pattern in JavaScript, see Holy Bat-Signal, Batman! Implementing the Observer Pattern in JavaScript.
With Bower: bower install observability.js --save
By default, observability.js provides a mixinObservability
object on the global
scope, which can be used as follows.
var gordon = { name: "James Gordon" };
mixinObservability(gordon);
Now gordon
has two new methods: registerObserver
, and notifyObservers
.
(function () {
function batSignal (villain) {
console.log("Batman is on his way to deal with " + villain.name);
}
gordon.registerObserver(batSignal);
})();
gordon.notifyObservers({ name: "Joker" });
// => Batman is on his way to deal with Joker
In addition to using observability on ordinary objects, you can also use it on object prototypes.
function PoliceOfficer (name) {
this.name = name;
}
mixinObservability(PoliceOfficer.prototype);
Now all PoliceOfficer
objects can register and notify observers, but the observers will be unique to the instances.
If you are using Angular.js, you probably want to take advantage of Angular's dependency injection. Just add the observability.js
module to your list of app dependencies.
angular.module("gothamApp", ["observability.js"]);
And then you can inject the observability
object as normal with Angular's DI.
angular.module("gothamApp").factory("gordon", function (mixinObservability) {
var gordon = { name: "James Gordon" };
mixinObservability(gordon);
return gordon;
});
Otherwise usage is the same as listed above.