Skip to content

Commit

Permalink
implement basic component system
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrsh committed Feb 25, 2017
1 parent 81a5e19 commit 2b3114f
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 9 deletions.
44 changes: 40 additions & 4 deletions dist/moon.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,14 @@
}
}
// It's a Component
if (components[tag] && components[tag].opts.functional) {
return createFunctionalComponent(tag, attrs, meta, children, components[tag]);
if (components[tag]) {
// Functional component
if (components[tag].opts.functional) {
return createFunctionalComponent(tag, attrs, meta, children, components[tag]);
} else {
// Provide the instance to diff engine
meta.component = components[tag];
}
}

return createElement(tag, "", attrs, children, meta);
Expand Down Expand Up @@ -305,6 +311,20 @@
return el;
};

/**
* Mounts a Component To The DOM
* @param {Object} node
* @param {Object} component
* @return {Object} DOM Node
*/
var createComponentFromVNode = function (node, component) {
var componentInstance = new component.CTor();
componentInstance.$el = node;
componentInstance.build();
callHook(componentInstance, 'mounted');
return componentInstance.$el;
};

/**
* Diffs Props of Node and a VNode, and apply Changes
* @param {Object} node
Expand Down Expand Up @@ -357,7 +377,7 @@
// No vnode, remove the node
parent.removeChild(node);
return null;
} else if (nodeName !== vnode.type) {
} else if (nodeName !== vnode.type && !vnode.meta.component) {
// Different types, replace it
var newNode = createNodeFromVNode(vnode, instance);
parent.replaceChild(newNode, node);
Expand All @@ -367,6 +387,17 @@
node.textContent = vnode.val;
return node;
} else if (vnode && vnode.type !== "#text" && vnode.meta.shouldRender) {

if (vnode.meta.component) {
// Detected a component
// If not mounted, create a new instance and mount it
// Then just skip diffing children
if (!node.__moon__) {
createComponentFromVNode(node, vnode.meta.component);
}
return node;
}

// Children May have Changed

// Diff props
Expand Down Expand Up @@ -1115,7 +1146,12 @@
* @param {Object} vnode
*/
Moon.prototype.patch = function (node, vnode, parent) {
diff(node, vnode, parent, this);
var newRootEl = diff(node, vnode, parent, this);
if (node !== newRootEl) {
// Root Node Changed, Apply Change in Instance
this.$el = newRootEl;
this.$el.__moon__ = this;
}
this.$initialRender = false;
};

Expand Down
Loading

0 comments on commit 2b3114f

Please sign in to comment.