Skip to content

Instantly share code, notes, and snippets.

@kawasako
Last active June 18, 2016 19:37
Show Gist options
  • Save kawasako/5f5eb972ab672b1c674ec4cdbae50fe8 to your computer and use it in GitHub Desktop.
Save kawasako/5f5eb972ab672b1c674ec4cdbae50fe8 to your computer and use it in GitHub Desktop.
import _ from 'underscore';
import { Promise } from 'es6-promise';
import HogeWidget from 'widgets/hogeWidget';
const widgets = {
hoge: HogeWidget
};
const widgetsInstances = [];
function parse(node, tree = { children: [] }) {
_.forEach(node.children, function(child) {
let next = tree;
// data-widgetがなければ階層を作らずそのまま子要素を処理する
if (!child.attributes['data-widget']) {
return parse(child, next);
}
let name = child.attributes['data-widget'].value.replace(/\s+/g, '');
let clazz = widgets[name];
if (!clazz) {
return parse(child, next);
}
// 新しいtreeの階層を作る
next = {
// 初期化の関数
initializer: function() {
// 子階層のinitializerを叩く
let promises = _.map(next.children, function(child) {
return child.initializer();
});
// initializerはPromiseを返す
return new Promise(function(resolve) {
// 子widgetのresolveを待つ
Promise.all(promises).then(function() {
// Elementとresolverを引数にnewさせる
let instance = new clazz(next.node, resolve);
widgetsInstances.push(instance);
}, function(err) {
console.error('initializer', err);
});
}, function(err) {
console.error('initializer', err);
});
},
node: child,
parent: tree,
children: []
};
// 生成した階層のobjectを処理中の階層の子階層として追加する
tree.children.push(next);
// 子階層を現在階層として更に子要素を処理する
return parse(child, next);
});
return tree;
}
// parse(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment