【发布时间】:2017-02-01 10:18:46
【问题描述】:
我只是想知道如何使用 JavaScript 创建一个可以在我的项目中多次使用的可重用组件。例如,如果我想创建一个可以在单个 HTML 页面上多次使用的小部件,那么该怎么办?以下是执行相同操作的示例。
【问题讨论】:
标签: javascript html plugins
我只是想知道如何使用 JavaScript 创建一个可以在我的项目中多次使用的可重用组件。例如,如果我想创建一个可以在单个 HTML 页面上多次使用的小部件,那么该怎么办?以下是执行相同操作的示例。
【问题讨论】:
标签: javascript html plugins
这是我所做的:
HTML:
<div id="ele1" class="myclass">
</div>
在这里,我采用了一个 html 容器元素,我想在其中添加创建自定义插件的所有要求。
JS:
(function() {
var ww = function(el) { // core constructor
// ensure to use the `new` operator
if (!(this instanceof ww))
return new ww(el);
// store an argument for this example
this.el = el;
};
// create `fn` alias to `prototype` property
ww.fn = ww.prototype = {
init: function () {}
};
// expose the library
window.ww = ww;
})();
要创建一个名为 fn 的原型并将其分配给特定元素,上述代码是必需的。
然后迭代 all 元素以调用特定类 myclass 的插件,如下所示:
document.addEventListener('DOMContentLoaded', function() {
for(var i=0; i<document.getElementsByClassName("weather").length; i++){
ww(document.getElementsByClassName("weather")[i]).WeatherWidget();
}
}, false);
现在我可以使用上面示例中的 ww.fn 为该元素分配任何方法,如下所示:
ww.fn.MyWidget = function () {
var me = this.el;
return new ww.fn.widgetConstruct(me);
};
这里,widgetConstruct()是包含组件所有业务逻辑的方法。
ww.fn.widgetConstruct = function(me){
function initialize(){
....
The component logic will go here
....
}
initialize();
}
如果您想查看完整示例,那么这是 Weather Widget
的 plnkr Demo【讨论】:
现代方法是使用 React.js、Angular 或 Vue.js 等框架。
React.js 正是为此而生的。
【讨论】: