【问题标题】:How to write a reusable JavaScript plugin code with ease of applying only a class?如何编写一个可重用的 JavaScript 插件代码,并且只应用一个类?
【发布时间】:2017-02-01 10:18:46
【问题描述】:

我只是想知道如何使用 JavaScript 创建一个可以在我的项目中多次使用的可重用组件。例如,如果我想创建一个可以在单个 HTML 页面上多次使用的小部件,那么该怎么办?以下是执行相同操作的示例。

【问题讨论】:

    标签: javascript html plugins


    【解决方案1】:

    这是我所做的:

    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

    【讨论】:

      【解决方案2】:

      现代方法是使用 React.js、Angular 或 Vue.js 等框架。

      React.js 正是为此而生的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2017-05-03
        • 2010-10-29
        • 2013-10-30
        • 1970-01-01
        • 2014-05-26
        相关资源
        最近更新 更多