Skip to content

Instantly share code, notes, and snippets.

@msrafi
Forked from sdepold/LICENSE.txt
Created November 6, 2012 23:03
Show Gist options
  • Save msrafi/4028288 to your computer and use it in GitHub Desktop.
Save msrafi/4028288 to your computer and use it in GitHub Desktop.
Javascript: 140byt.es -- addObserverMethods

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()
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()
})
}
}
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()})}}
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.
{
"name": "addObserverMethods",
"description": "Bind observer methods to an object.",
"keywords": [
"observer",
"listener"
]
}
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment