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);
  }
  //add listener
  myObject.started.add(onStarted);
  //dispatch signal passing custom parameters
  myObject.started.dispatch('foo', 'bar');
  //remove a single listener
  myObject.started.remove(onStarted);

Multiple Listeners

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

Stop Propagation (method 1)

  myObject.started.add(function(){
    myObject.started.stopPropagation();
  });
  myObject.started.add(function(){
    //won't be called since first listener stops propagation
    alert('second listener');
  });
  myObject.started.dispatch();

Stop Propagation (method 2)

  myObject.started.add(function(){
    return false; //stop propagation
  });
  myObject.started.add(function(){
    //won't be called since first listener stops propagation
    alert('second listener');
  });
  myObject.started.dispatch();
Clone this wiki locally