Skip to content
millermedeiros edited this page Nov 27, 2010 · 18 revisions

Few examples on how to use Signals for custom event dispatching, check the documentation for a a full reference of available methods and properties.

Setup code (required for all examples)

  //store local reference for brevity
  var Signal = signals.Signal;
  
  //custom object that dispatch signals
  var myObject = {
    started : new Signal(),
    stopped : new Signal()
  };

Single Listener

  function onStarted(param1, param2){
    alert(param1 + param2);
  }
  myObject.started.add(onStarted); //add listener
  myObject.started.dispatch('foo', 'bar'); //dispatch signal passing custom parameters
  myObject.started.remove(onStarted); //remove a single listener

Multiple Listeners

  function onStopped(){
    alert('stopped');
  }
  function onStopped2(){
    alert('stopped listener 2');
  }
  myObject.stopped.add(onStopped);
  myObject.stopped.add(onStopped2);
  myObject.stopped.dispatch();
  myObject.stopped.removeAll(); //remove all listeners of the `stopped` signal

Stop Propagation (method 1)

  myObject.started.add(function(){
    myObject.started.halt(); //prevent next listeners on the queue from being executed
  });
  myObject.started.add(function(){
    alert('second listener'); //won't be called since first listener stops propagation
  });
  myObject.started.dispatch();

Stop Propagation (method 2)

  myObject.started.add(function(){
    return false; //if handler returns `false` will also stop propagation
  });
  myObject.started.add(function(){
    alert('second listener'); //won't be called since first listener stops propagation
  });
  myObject.started.dispatch();

Multiple Dispatchs

  var i = 0;
  myObject.started.add(function(){
    i += 1;
    alert(i);
  });
  myObject.started.dispatch(); //will alert 1
  myObject.started.dispatch(); //will alert 2

Multiple Dispatchs + addOnce()

  var i = 0;
  myObject.started.addOnce(function(){
    i += 1;
    alert(i);
  });
  myObject.started.dispatch(); //will alert 1
  myObject.started.dispatch(); //nothing happens

Enable/Disable Signal

  var i = 0;
  myObject.started.add(function(){
    i += 1;
    alert(i);
  });
  myObject.started.dispatch(); //will alert 1
  myObject.started.disable();
  myObject.started.dispatch(); //nothing happens
  myObject.started.enable();
  myObject.started.dispatch(); //will alert 2

Set execution context of the listener handler

  var foo = 'bar';
  var obj = {
    foo : 10
  };
  
  function handler1(){
    alert(this.foo);
  }
  function handler2(){
    alert(this.foo);
  }
  //note that you cannot add the same handler twice to the same signal without removing it first
  myObject.started.add(handler1); //default execution context
  myObject.started.add(handler2, obj); //set a different execution context
  myObject.started.dispatch(); //first handler will alert "bar", second will alert "10".

Back to Home

Clone this wiki locally