2014-01-13 19 views
0

也許標題是不太有用的理解什麼是問題,但我會嘗試以明確的方式我會實現解釋。凡與兼容RequireJS插入內部(實用)對象/ AMD的JavaScript庫

正在關注Jeremy Kahn模板(您可以在GitHub找到它)我創建了一個與RequireJS和AMD兼容的庫。

庫如下所示(跳過簡碼)。

;(function(global, undefined) { 

    var Fn = Function, GLOBAL = new Fn('return this')(); 

    function initLSKitCore(context, _) { 

     'use strict'; 

     // private vars here... 

     var LSKit = context.LSKit = function(options) { 

      this.groups = []; 

      return this; 
     }; 

     /** 
     * Add a new Group 
     */ 
     LSKit.prototype.addGroup = function(groupId) { 

      // implementation here... 
     }; 

     // other prototype methods... 
    } 

    var initLSKit = function(context, deps) { 

     var context = deps ? {} : global; 

     var _ = (deps && deps.underscore) ? deps.underscore : context._; 

     initLSKitCore(context, _); 

     // other modules here... 

     return context.LSKit; 
    }; 

    if (typeof define === 'function' && define.amd) { 

     define(["underscore"], function (Underscore) { 

      var underscoreSupportsAMD = (Underscore != null); 

      // Some versions of Underscore.js support AMD, others don't. 
      // If not, use the `_` global. 
      var deps = { underscore: underscoreSupportsAMD ? Underscore : _ }; 
      var SLKit = initLSKit({}, deps); 
      return SLKit; 
     }); 
    } else { 
     initLSKit(this); 
    } 

}(this)); 

groups陣列使得能夠存儲,檢索或獲得這樣定義Group對象。

function Group(identifier, name){ 
    this.identifier = identifier; 
    this.name = name; 
    this.internalList = []; 
}; 

根據我的實際要求如下。我想用Group作爲一個內部類(我知道的術語是不正確的,因爲它實際上是一個內部對象)。那麼,在我的庫中插入第二個片段(即Group構造函數)的正確位置在哪裏?

回答

1

按照你的模板,你只需要在initLSkit方法

if (typeof define === 'function' && define.amd) { 
    define(["underscore", "lib/group"], function (Underscore, Group) { 

     var underscoreSupportsAMD = (Underscore != null); 

     // Some versions of Underscore.js support AMD, others don't. 
     // If not, use the `_` global. 
     var deps = { underscore: underscoreSupportsAMD ? Underscore : _, Group: Group }; 
     var SLKit = initLSKit({}, deps); 
     return SLKit; 
    }); 
} else { 
    initLSKit(this, { Group: global.Group }); 
} 

我相信它始終是更好地注入你的依賴注入它。所以我在使用全局上下文時也會注入下劃線。添加依賴解析邏輯initLSKit裏面是你的業務邏輯中只有噪音(關注點分離FTW)。

如果沒有AMD加載,你也可以在本地申報到您的模塊是這樣的:

;(function(global, undefined) { 

    var Fn = Function, GLOBAL = new Fn('return this')(); 

    // Just create it here, it'll be available inside your module 
    // and won't be reachable from outside the module (private). 
    var Group = function() {}; 

// etc... 
+0

感謝您的答覆。在這種情況下,我想將其用作內部課程。可能嗎? –

+0

什麼是最好的方法? –

+0

然後只需在關閉中聲明它,它將僅在本地可用。 –

相關問題