File: js/__improved-model/model-swtch/index.js
/* jshint ignore:start */
if (typeof define !== 'function') { var define = require('amdefine')(module) }
/* jshint ignore:end */
define(function defImprovedModelSwtch(require, exports, module) {
'use strict';
var swtch = require('swtch'),
_ = require('lodash');
// the condition builder
var buildCondition = require('./build-condition'),
// the callback builder
buildCallback = require('./build-callback');
// direct reference to original methods
var _initializeSwtch = swtch.prototype.initialize,
_when = swtch.prototype.when;
var modelSwtch = module.exports = swtch.extend({
initialize: function initializeModelSwtch(cases, options) {
// save reference to the model
// do this before initializing the swtch
// as swtch initialization tries to call
// when method for each of the cases.
this.model = options.model;
// parse out cases
var _cases;
if (_.isArray(cases)) {
// array of condition definiitons.
_cases = cases;
} else {
// object that has to be parsed out.
_cases = [];
_.each(cases, function (action, criteria) {
_cases.push({
condition: criteria,
value : action,
});
});
}
// the original intialize method only takes the cases argument.
_initializeSwtch.call(this, _cases);
},
/**
* Override the when method in order to introduce a condition builder.
*
*/
when: function modelSwtchWhen(criteria, action, context) {
var args = _.toArray(arguments);
if (criteria !== 'default') {
// build the condition
var condition = buildCondition(this.model, criteria),
// build the callback
callback = buildCallback(this.model, action);
// rebuild the arguments
args = [condition, callback].concat(args.slice(2));
}
// invoke the original when method
return _when.apply(this, args);
}
});
});