Code coverage report for src/ObjectEventTarget.js

Statements: 79.68% (149 / 187)      Branches: 69.16% (74 / 107)      Functions: 75.86% (22 / 29)      Lines: 79.68% (149 / 187)      Ignored: none     

All files » src/ » ObjectEventTarget.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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392                                  1       1 1 1     1 1 1 5   1     1 9     9         1 1 1           17   1         94 126 47 16 16   47     47   1   35 35     35 35 5   30       19     5 5 4           1 1     9   9 4       4 4   5     1                                                                         1       12         12   12 12 2   10 10           10         10 10 10     10 10 10   10     10 10 10   10 10 10 10 10 10     10     10     10 3                 7     7     1     1       1 21         1   1 9 9     1         1 12 12       1 1   1 21 2     19     19     19     19 1       19   19 19 19 19 19   1 1 1       11     11     11     11   4 4       11 11 11 11     11 4 4 4         4 4 4         4 4 4 2 2         1   2   1   3       1 1 2 2 9 9           2       1   1       1       1 1 1   1 1 1                 1              
// Add a ObjectEventTarget with a prototype that can be used
// by any object in the JavaScript context, to add, remove and trigger
// events.
// Example:
// ```
// function Foo(){}
// Foo.prototype = ObjectEventTarget.prototype;
// foo = new Foo();
// foo.addEventListener('dosomething', function(){
//   console.log(this, 'do something');
// });
// foo.dispatchEvent({type: 'dosomething'});
// // [Foo object], do something
// ```
//
// In old browsers that doesn't support enumerable property definition, the prototype
// methods will be iterated when you do for in, so don't forget to use the hasOwnProperty
(function(root) {
  'use strict';
 
  // Load options that can be setup before loading the library
  var options = root.ObjectEventTarget && root.ObjectEventTarget.options || {};
  var DEBUG = root.DEBUG || options.DEBUG;
  var VERSION = options.VERSION || 'development';
 
  // Named object what contains the events queue for an object
  var EventsMap = options.EventsMap;
  Eif (!EventsMap){
    EventsMap = function EventsMap(type, callback){
      this[type] = [callback];
    };
    EventsMap.prototype = Object.prototype;
  }
 
  function typeErrors(type, callback){
    Iif (typeof type !== 'string' || type.length === 0){
      throw new TypeError('Type must be a string and can\'t be empty');
    }
    Iif (typeof callback !== 'function'){
      throw new TypeError('Callback must be a function');
    }
  }
 
  var WeakMap = options.WeakMap || root.WeakMap;
  Eif (!WeakMap) {
    WeakMap = function WeakMapArrayShim(){
      // A simple shim for WeakMap, only for usage in this lib, so it doesn't
      // support all features from a WeakMap, and it uses Array.indexOf for
      // search that isn't very performatic but allow us to have support in
      // old browsers
 
      this.map = [];
    };
    var find = function (arr, key){
      // Search for a meta element for the WeakMap shim, and if found
      // move this element for the begin of the array, to optimize usual
      // repetitive usage of the same object, and fast find the most used
 
      for (var m = arr.length - 1, i = m; i >= 0; i--){
        if (arr[i].key === key) {
          if (i !== m){
            var r = arr.splice(i, 1);
            arr.push(r[0]);
          }
          return arr[m];
        }
      }
      return;
    };
    WeakMap.prototype = {
      get: function (obj){
        var meta = find(this.map, obj);
        return meta && meta.value;
      },
      set: function (obj, value){
        var meta = find(this.map, obj);
        if (meta){
          meta.value = value;
        } else {
          this.map.push({key: obj, value: value});
        }
      },
      has: function (obj){
        return !!find(this.map, obj);
      },
      delete: function (obj){
        var meta = find(this.map, obj);
        if (meta) {
          this.map.pop();
        }
      }
    };
  }
 
  var map = new WeakMap();
  function add(obj, type, callback){
    // Add a object with a event type and callback to a weakmap
 
    typeErrors(type, callback);
 
    if (map.has(obj)) {
      Iif (map.get(obj)[type]) {
        map.get(obj)[type].push(callback);
        return;
      }
      map.get(obj)[type] = [callback];
      return;
    }
    map.set(obj, new EventsMap(type, callback));
  }
 
  function remove(obj, type, callback){
    // Removes the callback from the event queue and keep the memory clean
    // removing empty events queue and objects without events from the map
 
    typeErrors(type, callback);
 
    if (!map.has(obj)){
      return;
    }
    var eventsMap = map.get(obj);
    var eventQueue = eventsMap[type];
    if (!eventQueue){
      return;
    }
    var pos = eventQueue.indexOf(callback);
    if (pos === -1){
      return;
    }
    // Remove all matching callbacks
    while(pos !== -1){
      eventQueue.splice(pos, 1);
      pos = eventQueue.indexOf(callback);
    }
 
    // Remove the propertie with array when the array is empty
    if (eventQueue.length === 0){
      delete eventsMap[type];
    }
 
    // If the eventsMap isn't empty don't remove from the objects weakmap
    for (var prop in eventsMap)
    if (eventsMap.hasOwnProperty(prop)) {
      return;
    }
    map.delete(obj);
  }
 
  function dispatch(obj, event){
    // Dispatch a queue of events of the tye passed inside the event object
 
    // Check if the event is a valid object
    Iif (!event || typeof event.type !== 'string'){
      throw new TypeError('Illegal invocation');
    }
 
    // Init the event
    ObjectEvent.prototype.initEvent.call(event);
 
    var eventsMap = map.get(obj);
    if (!eventsMap) {
      return true;
    }
    var eventsQueue = eventsMap[event.type];
    Iif (!eventsQueue) {
      return true;
    }
 
    // Prevent event to be triggered more then one time
    // if you preventDefault the event should be triggered again
    Iif (event.path.length !== 0 && event.returnValue) {
      return true;
    }
 
    // Prevent forcing event new values after begin the callback queue calls
    var returnValue = true;
    var cancelable = !!event.cancelable;
    var type = event.type;
 
    // Reset and add the obj instance to path
    event.path.length = 0;
    Eif (event.path.push){
      event.path.push(obj);
    }
    var path = event.path;
 
    // Clone the array before iterate, avoid event changing the queue on fly
    eventsQueue = eventsQueue.slice();
    try{
      for (var i = 0, m = eventsQueue.length; i < m; i++) {
        // Ensure non-writetible event properties states
        event.eventPhase = ObjectEvent.prototype.AT_TARGET;
        event.cancelable = cancelable;
        event.returnValue = returnValue;
        event.defaultPrevented = !returnValue;
        event.type = type;
        event.path = path;
 
        // Call next event, using the object instance as context
        eventsQueue[i].call(obj, event);
 
        // Update the returnValue when default has been prevented
        returnValue = returnValue && !(cancelable && event.defaultPrevented);
 
        // Stop the immidiate propagation and return the returnValue
        if (event.immediatePropagationStopped) {
          return returnValue;
        }
      }
    }catch(e){
      setTimeout(function(){
        throw e;
      });
    }
 
    event.eventPhase = ObjectEvent.prototype.NONE;
 
    // true if default hasn't been prevented
    return returnValue;
  }
 
  function ObjectEventTarget(){
    // It's a singleton, once we have the instance for the prototype
    // the user should not be allowed to create new instances
    Iif (ObjectEventTarget.prototype.constructor === ObjectEventTarget){
      throw new TypeError('Illegal constructor');
    }
 
    function illegalIvovation(context){
      Iif (context === ObjectEventTarget.prototype) {
        throw new TypeError('Illegal invocation');
      }
    }
 
    this.constructor = ObjectEventTarget;
 
    this.addEventListener = function(type, callback){
      illegalIvovation(this);
      add(this, type, callback);
    };
 
    this.removeEventListener = function(type, callback){
      illegalIvovation(this);
      remove(this, type, callback);
    };
 
    this.dispatchEvent = function(event){
      illegalIvovation(this);
      return dispatch(this, event);
    };
  }
 
  ObjectEventTarget.prototype = Object.prototype;
  ObjectEventTarget.prototype = new ObjectEventTarget();
 
  function ObjectEvent(type, options){
    if (arguments.length === 0){
      throw new TypeError('Failed to construct \'ObjectEvent\': An event name must be provided.');
    }
 
    options = options || {};
 
    // Time that the event has created
    this.timeStamp = Date.now();
 
    // Allow preventDefault()
    this.cancelable = options.cancelable === true;
 
    // Add custom details to the event
    if (typeof options.detail !== 'undefined') {
      this.detail = options.detail;
    }
 
    // Phase of the event
    this.eventPhase = ObjectEvent.prototype.NONE;
 
    this.path = [];
    this.immediatePropagationStopped = false;
    this.defaultPrevented = false;
    this.returnValue = true;
    this.type = String(type);
  }
  ObjectEvent.prototype.AT_TARGET = 2;
  ObjectEvent.prototype.NONE = 0;
  ObjectEvent.prototype.initEvent = function() {
    // Init event if it has some propertie wrong, fix it
 
    // Time that the event has created
    this.timeStamp = this.timeStamp || Date.now();
 
    // Allow preventDefault()
    this.cancelable = this.cancelable === true;
 
    // Phase of the event
    this.eventPhase = ObjectEvent.prototype.NONE;
 
    // Cleanup the path and add the instance to the event path
    if (!this.path || !this.path.push) {
      // Opera and other browsers can throw exception if you are using native Event instance
      try{
        this.path = [];
      }catch(e){}
    }
 
    this.immediatePropagationStopped = this.immediatePropagationStopped === true;
    this.defaultPrevented = this.cancelable && this.defaultPrevented === true;
    this.returnValue = true;
    this.type = String(this.type);
 
    // Add methods when they don't exist
    if (!(this instanceof ObjectEvent)){
      Eif (!this.hasOwnProperty('initEvent')){
        var nativeInitEvent = this.initEvent || function(){};
        this.initEvent = function(){
          nativeInitEvent.apply(this, arguments);
          ObjectEvent.prototype.initEvent.apply(this, arguments);
        };
      }
      Eif (!this.hasOwnProperty('preventDefault')){
        var nativePreventDefault = this.preventDefault || function(){};
        this.preventDefault = function(){
          nativePreventDefault.apply(this, arguments);
          ObjectEvent.prototype.preventDefault.apply(this, arguments);
        };
      }
      Eif (!this.hasOwnProperty('stopImmediatePropagation')){
        var nativeStopImmediatePropagation = this.stopImmediatePropagation || function(){};
        this.stopImmediatePropagation = function(){
          nativeStopImmediatePropagation.apply(this, arguments);
          ObjectEvent.prototype.stopImmediatePropagation.apply(this, arguments);
        };
      }
    }
  };
  ObjectEvent.prototype.preventDefault = function(){
    // Prevent the default result, makes the dispatchEvent returns false
    this.defaultPrevented = !!this.cancelable;
  };
  ObjectEvent.prototype.stopImmediatePropagation = function(){
    // Don't allow the next callback to be called
    this.immediatePropagationStopped = true;
  };
 
  // Prevent enumerable prototype when supported by the browser
  Eif (Object.defineProperties){
    var definePropertiesArgs = function (prototype){
      var props = {};
      for (var k in prototype) {
        Eif (prototype.hasOwnProperty(k)){
          props[k] = {
            value: prototype[k],
            enumerable: false
          };
        }
      }
      return [prototype, props];
    };
 
    // ObjectEvent remove enumerable prototype
    Object.defineProperties.apply(Object, definePropertiesArgs(ObjectEvent.prototype));
    // ObjectEventTarget remove enumerable prototype
    Object.defineProperties.apply(Object, definePropertiesArgs(ObjectEventTarget.prototype));
  }
 
  // Expose the ObjectEventTarget to global
  Iif (typeof window === 'undefined'){
    // jshint node:true
    root = global;
  }
  ObjectEventTarget.VERSION = VERSION;
  root.ObjectEventTarget = ObjectEventTarget;
  root.ObjectEvent = ObjectEvent;
 
  ObjectEventTarget.DEBUG = DEBUG;
  Eif (DEBUG){
    ObjectEventTarget.__debug = {
      EventsMap: EventsMap,
      typeErrors: typeErrors,
      WeakMap: WeakMap,
      map: map
    };
  }
 
  // Export as module to nodejs
  Iif (typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
    module.exports = {
      ObjectEventTarget: ObjectEventTarget,
      ObjectEvent: ObjectEvent
    };
  }
})(this);