-
-
Save HendrikRoth/85471c5f2da44137e097 to your computer and use it in GitHub Desktop.
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
m.createComponent = function(proto) { | |
function _component(attrs, children) { | |
// always return a fresh instance, allows for call without new | |
if(!(this instanceof _component)) { | |
return new _component(attrs, children); | |
} | |
if(!children && Array.isArray(attrs)) { | |
children = attrs; | |
attrs = null; | |
} else { | |
if(!attrs) { | |
attrs = null | |
} | |
children = []; | |
} | |
// attach properties (immutable) | |
Object.keys(proto).forEach(function(key) { | |
var val = proto[key]; | |
this[key] = (typeof val === 'function')? val.bind(this): val; | |
}, this); | |
// attach mutable state | |
this.attrs = attrs; | |
this.state = this.getInitialState ? this.getInitialState() : null; | |
if(attrs && attrs.state) { | |
Object.keys(this.state).forEach(function(key) { | |
attrs.state[key] = this.state[key]; | |
}, this); | |
this.state = attrs.state; | |
delete attrs.state; | |
} | |
// attach any children | |
this.children = children; | |
this.tag = "custom"; | |
// finalize any attached children on finalize | |
this._finalize = function() { | |
this.children.forEach(function(child) { | |
child._finalize(); | |
}); | |
this.onunload && this.onunload(); | |
} | |
// initialize this | |
if(this.initialize) { | |
this.initialize(); | |
} | |
} | |
_component.prototype = Object.create(m.createComponent.prototype); | |
_component.prototype.constructor = _component; | |
return _component; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment