Skip to content

Instantly share code, notes, and snippets.

@webcss
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save webcss/6319631bf5eac756b4c8 to your computer and use it in GitHub Desktop.
Save webcss/6319631bf5eac756b4c8 to your computer and use it in GitHub Desktop.
mithril component implementation (adapted from James Long - Bloop)
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