【问题标题】:JQuery Plugin Pattern - Code Organization for multiple scriptsJQuery Plugin Pattern - 多个脚本的代码组织
【发布时间】:2013-08-13 05:45:12
【问题描述】:

我正在使用基于此处列出的轻量级插件模式的 JQuery 开发客户端。

https://github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.basic.plugin-boilerplate.js

我一直在处理一个文件,但由于超过 1000 行代码,它变得臃肿不堪。所以我决定拆分脚本,但我找不到使用 jQuery 保存多个脚本的最佳实践。

我的主要脚本如下:

;(function($, window, document, undefined) {
   function MainClass(){
       this.other = new Otherclass(); // Otherclass is defined in separate script
   }

   MainClass.prototype = {
   ...
   }

   $.fn.mainclass = function(){
   ...
   }
})(jQuery, window, document);

HTML 如下:

<html>
   <head>
      // JQuery included
      <script type="text/javascript" src="mainclass.js></script>
      <script>
      $(function() {
         $("body").mainclass();
      });
      </script> 
   </head>
</html>

问题:我需要在单独的文件中定义 otherclass。实现这一目标的最佳方法是什么?如果插件模式不打算有多个脚本,还有其他适合这个的做法吗?

谢谢。

【问题讨论】:

    标签: javascript jquery code-organization plugin-pattern


    【解决方案1】:

    您使用的模块模式是朝着正确方向迈出的良好第一步。插件模式的真正目的是为给定的一组元素封装一个特定的功能,并且很好地遵循了开放/封闭原则,通过设计(为扩展而开放)。但是,由于它的主要行为是作为 jQuery 对象的扩展方法,因此它不是多对象交互的好方法。

    我能够将 JavaScript 拆分为页面/多个文件的一件事是结合使用命名空间和模块扩充/导入/导出。

    命名空间非常适合导入和取消引用应用程序的其他部分,模块模式有助于选择暴露并导出适量的对象可重用成员。从那里,我可以取消引用命名空间中的任何对象,从中创建新实例,等等:

    //In some common site-wide file, declare a common namespace and known base objects within it:
    
    var App = {
       View: {},
       Utilities: {}
    };
    
    // view.js
    App.View = (function($, window, document, undefined) {
        var localProp = "Hi, i'm a private property for App.View to access";
    
        function doSomething(){
           // a private method for use
        }
    
        return {
           reuseableMethod: function() {
              // exported for access through App.View.reusableMethod()
           }
        };
    
    })(jQuery, window, window.document, undefined);
    
    // another script, more specific, different file
    // NOTE: the import and export of App.View and view
    (function($, window, document, view) {
       // consume your other objects after importing them
       var me = Object.create(view);
    
       me.reuseableMethod();
    
       function localFunction() {
         //do something private
       }
    
    })(jQuery, window, window.document, App.View);
    

    【讨论】:

    • 您好,到目前为止,我一直在充分利用此解决方案。我在这里使用 Object.create 有点困惑,因为没有它,代码的工作方式相同。您能否详细说明其目的?
    • Object.create 用于创建使用对象表示法声明的对象的新实例。当一个对象被声明为一个函数时,你可以使用'new'关键字创建它的一个新实例;但是,事实并非如此。因为 App.View 返回一个对象,所以创建 this 实例的最佳方法是通过 Object.create 函数。
    猜你喜欢
    • 2011-02-12
    • 2018-02-03
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多