onlooker

observer

Usage no npm install needed!

<script type="module">
  import onlooker from 'https://cdn.skypack.dev/onlooker';
</script>

README

onlooker

add observer functionality to any object

var ObserverMixin = require('onlooker');

var Person = function(name) {
    this.name = name;
    this.on('nameChange', this.shoutName);
    return this;
}

ObserverMixin(Person.prototype);

Person.prototype.shoutName = function(newName, oldName) {
    console.log('MY NAME IS', newName.toUpperCase());
};

Person.prototype.changeName = function(name) {
    var oldName = this.name;
    this.name = name;
    this.trigger('nameChange', this.name, oldName);
};
var tintin = new Person('Tintin');

tintin.changeName('Snowy');

// logs: MY NAME IS SNOWY

adds on, off, and trigger methods to the specified object.

supports space delimited event names - e.g:

obj.trigger('created updated', args);