Code coverage report for lib/module/events.js

Statements: 100% (28 / 28)      Branches: 100% (12 / 12)      Functions: 100% (5 / 5)      Lines: 100% (26 / 26)      Ignored: none     

All files » lib/module/ » events.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85          1                           1       37 34 34             37 3 3 2       34     37                 1 11 11     1     11                 11 10     11     1 29   18 18 18     1 1
 
/**
 * Module Dependencies
 */
 
var events = require('event');
 
/**
 * Exports
 */
 
/**
 * Registers a event listener.
 *
 * @param  {String}   name
 * @param  {String}   module
 * @param  {Function} cb
 * @return {View}
 */
exports.on = function(name, module, cb) {
 
  // cb can be passed as
  // the second or third argument
  if (arguments.length === 2) {
    cb = module;
    module = null;
  }
 
  // if a module is provided
  // pass in a special callback
  // function that checks the
  // module
  if (module) {
    events.prototype.on.call(this, name, function() {
      if (this.event.target.module() === module) {
        cb.apply(this, arguments);
      }
    });
  } else {
    events.prototype.on.call(this, name, cb);
  }
 
  return this;
};
 
/**
 * Fires an event on a view.
 *
 * @param  {String} name
 * @return {View}
 */
exports.fire = function(name) {
  var _event = this.event;
  var event = {
    target: this,
    propagate: true,
    stopPropagation: function(){ this.propagate = false; }
  };
 
  propagate(this, arguments, event);
 
  // COMPLEX:
  // If an earlier event object was
  // cached, restore the the event
  // back onto the view. If there
  // wasn't an earlier event, make
  // sure the `event` key has been
  // deleted off the view.
  if (_event) this.event = _event;
  else delete this.event;
 
  // Allow chaining
  return this;
};
 
function propagate(view, args, event) {
  if (!view || !event.propagate) return;
 
  view.event = event;
  events.prototype.fire.apply(view, args);
  propagate(view.parent, args, event);
}
 
exports.fireStatic = events.prototype.fire;
exports.off = events.prototype.off;