Created
July 16, 2014 02:10
-
-
Save JaapRood/ea55b11841d6b004fda9 to your computer and use it in GitHub Desktop.
ampersand-state mixin to use 'state' prop instead of children to get correct behaviour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var State = require('ampersand-state'), | |
_ = require('lodash'); | |
module.exports = function(childModels) { | |
if (!childModels) childModels = {}; | |
var props = {}; | |
_.each(childModels, function(def, name) { | |
props[name] = 'state'; | |
}); | |
return { | |
props: props, | |
set: function(key, value, options) { | |
// Replicating a bit of the source so we can support all set | |
var attrs; | |
// Handle both `"key", value` and `{key: value}` -style arguments. | |
if (_.isObject(key) || key === null) { | |
attrs = key; | |
options = value; | |
} else { | |
attrs = {}; | |
attrs[key] = value; | |
} | |
options = options || {}; | |
// if a child isn't set yet and only an object is given, create an instance | |
_.each(childModels, function(def, name) { | |
if (!this[name] && attrs[name] && !attrs[name] instanceof def) { | |
attrs[name] = new def(attrs[name], options); | |
} | |
}); | |
// defer rest to the original implementation | |
return State.prototype.set.call(this, attrs, options); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment