Code coverage report for src/wreqr.commands.js

Statements: 100% (22 / 22)      Branches: 100% (8 / 8)      Functions: 100% (6 / 6)      Lines: 100% (22 / 22)     

All files » src/ » wreqr.commands.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          1     1         17   17 17   17 17         6 6   6 3   3             9     9 2     9           17   17 17 15   2     17          
// Wreqr.Commands
// --------------
//
// A simple command pattern implementation. Register a command
// handler and execute it.
Wreqr.Commands = (function(Wreqr){
  "use strict";
 
  return Wreqr.Handlers.extend({
    // default storage type
    storageType: Wreqr.CommandStorage,
 
    constructor: function(options){
      this.options = options || {};
 
      this._initializeStorage(this.options);
      this.on("handler:add", this._executeCommands, this);
 
      var args = Array.prototype.slice.call(arguments);
      Wreqr.Handlers.prototype.constructor.apply(this, args);
    },
 
    // Execute a named command with the supplied args
    execute: function(name, args){
      name = arguments[0];
      args = Array.prototype.slice.call(arguments, 1);
 
      if (this.hasHandler(name)){
        this.getHandler(name).apply(this, args);
      } else {
        this.storage.addCommand(name, args);
      }
 
    },
 
    // Internal method to handle bulk execution of stored commands
    _executeCommands: function(name, handler, context){
      var command = this.storage.getCommands(name);
 
      // loop through and execute all the stored command instances
      _.each(command.instances, function(args){
        handler.apply(context, args);
      });
 
      this.storage.clearCommands(name);
    },
 
    // Internal method to initialize storage either from the type's
    // `storageType` or the instance `options.storageType`.
    _initializeStorage: function(options){
      var storage;
 
      var StorageType = options.storageType || this.storageType;
      if (_.isFunction(StorageType)){
        storage = new StorageType();
      } else {
        storage = StorageType;
      }
 
      this.storage = storage;
    }
  });
 
})(Wreqr);