我已经尝试推出我自己的HyperScript实现。我有兴趣听取任何改善这项建议的建议,或向我指出仍在维持的任何其他更佳的执行方法。我检查了HyperScript项目,但它似乎没有任何最近的更新,所以我尝试了如下:
var DOM = {
h: function(tagName, props, children) {
var element = document.createElement(tagName);
if (props) {
for (var item in props) {
element[item] = props[item];
}
}
if (children && Array.isArray(children) && children.length > 0) {
children.forEach(function(child) {
element.appendChild(child);
});
}
return element;
},
div: function(props, children) {
return this.h('div', props, children);
},
label: function(props, children) {
return this.h('label', props, children);
},
input: function(props, children) {
return this.h('input', props, children);
},
button: function(props, children) {
return this.h('button', props, children);
},
li: function(props, children) {
return this.h('li', props, children);
}
};
用法:
DOM.button({ className: "destroy" });
发布于 2016-02-19 23:42:44
这类库的有趣之处在于它们的实现很有趣。可悲的是,和他们一起工作并不是很有趣。从长远来看,您将乞求类似标记的语法。
但不管怎样,
div: function(props, children) {
return this.h('div', props, children);
},
label: function(props, children) {
return this.h('label', props, children);
},
input: function(props, children) {
return this.h('input', props, children);
},
button: function(props, children) {
return this.h('button', props, children);
},
li: function(props, children) {
return this.h('li', props, children);
}
这可以简化为元素名称的列表。您可以运行它,并为每个名称分配一个函数给DOM
。
['div', 'li', ...].forEach(elementName => {
DOM[elementName] = function(props, children){
return this.h(elementName, props, children);
};
});
至于您的h
函数,您应该使用hasOwnProperty
来保护for-in
,以避免对原型元素进行迭代。或者,您可以使用Object.keys
和forEach
。此外,当调试时,沉默错误是可怕的。如果用户传入的不是数组,最好立即通知他们。在下面的代码中,它只捕获假值。其他任何东西,比如非数组或其他东西,都会抛出,因为forEach
需要一个数组。
h: function(tagName, props, children) {
var element = document.createElement(tagName);
Object.keys(props || []).forEach( prop => {
element[prop] = props[prop];
});
(children || []).forEach(child => {
element.appendChild(child);
});
return element;
},
https://codereview.stackexchange.com/questions/120559
复制相似问题