« Back to Index

140byt.es – addObserverMethods

View original Gist on GitHub

LICENSE.txt

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2011 Sascha Depold http://depold.com

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

README.md

addObserverMethods

The function adds everything that is needed to an object. It will get a event-callbacks-map, an observer/listener method (on) and a trigger method (fire).

Usage

  var obj = {
    walk: function() {
      // do smth
      this.fire('walk')
    }
  }

  addObserverMethods(obj)

  obj.on('walk', function() {
    alert('it moved!')
  })

  obj.walk()

Or use it with a prototype:

  var Player = function(){
    addObserverMethods(this)
  }

  Player.prototype.walk = function() {
    // do smth
    this.fire('walk')
  }

  var player = new Player()
  player.on('walk', function() {
    alert('it moved!')
  })
  player.walk()

annotated.js

function(
  a // an object / instance
) {
  a.l = {};                 // eventName - listeners - map
  a.on = function(          // the observer method
    b,                      // the event name
    c                       // the callback
  ) {
    a.l[b] = a.l[b] || [];  // init array for current event name
    a.l[b].push(c)          // save callback for the event name
  };
  a.fire = function(        // the trigger method
    b                       // the event name
  ) {
    // iterate over the event name's callbacks and exec them
    (a.l[b] || []).forEach(function(a) {
      a()
    })
  }
}

index.js

function(a){a.l={};a.on=function(b,c){a.l[b]=a.l[b]||[];a.l[b].push(c)};a.fire=function(b){(a.l[b]||[]).forEach(function(a){a()})}}

package.json

{
  "name": "addObserverMethods",
  "description": "Bind observer methods to an object.",
  "keywords": [
    "observer",
    "listener"
  ]
}

test.html

<!DOCTYPE html>
<title>addObserverMethods</title>
<script>
  var addObserverMethods = function(a){a.l={};a.on=function(b,c){a.l[b]=a.l[b]||[];a.l[b].push(c)};a.fire=function(b){(a.l[b]||[]).forEach(function(a){a()})}}

  var Player = function(){
    addObserverMethods(this)
  }

  Player.prototype.walk = function() {
    // do smth
    this.fire('walk')
  }

  var player = new Player()

  player.on('walk', function() {
    alert('it moved!')
  })

  player.walk()
</script>