2012-07-08 48 views
5

我不確定如何在模塊化(RequireJs)Backbone環境中使用命名空間。如何在Requirebone中使用Backbone中的命名空間

我已經想了一下它如何可能看起來像但我完全不確定這是否是正確的方式。

app.js(過得去main.js執行)

define('App', ['underscore', 'backbone', 'Router'], function(_, Backbone, Router){ 
    function initialize(){ 
     var app = {}; // app is the global namespace variable, every module exists in app 

     app.router = new Router(); // router gets registered 

     Backbone.history.start(); 
    } 

    return { initialize: initialize } 
}); 

messages.js

define('MessageModel', ['underscore', 'backbone', 'App'], function(_, Backbone, App){ 
    App.Message.Model; // registering the Message namespace with the Model class 

    App.Message.Model = Backbone.Model.extend({ 
     // the backbone stuff 
    }); 

    return App; 
}); 

這是正確的做法或完全是我的錯誤的方式(如果是,請糾正我!)

回答

5

看看TODO Backbone + requireJs示例:

https://github.com/addyosmani/todomvc

+0

嗨,我查看了代碼。這是我目前使用RequireJs的方式,但是我錯過了命名空間(總是有另一個變量沒有「全局」之一) – 2012-07-08 09:25:10

+0

鏈接不再工作:(任何想法在哪裏檢索該資源? – lucke84 2013-01-21 17:35:59

+1

http://addyosmani.github.com/todomvc/dependency-examples/backbone_require/ – 2013-01-21 17:40:02

1

我是新來的骨幹,以測試它,但剛讀來自requirejs文檔的片段。

模塊不同於傳統的腳本文件,因爲它定義了一個良好範圍的對象,避免污染全局名稱空間。它可以顯式地列出它的依賴關係,並獲得這些依賴關係的句柄,而不需要引用全局對象,而是接收依賴關係作爲定義模塊的函數的參數。 RequireJS中的模塊是模塊模式的擴展,其優點是不需要全局變量來引用其他模塊。

對我來說,聽起來好像在使用requirejs時,你可以忘記所有關於命名空間的事情,就像requirejs處理它一樣。您只需以不同的方式訪問它。當你想從另一個模塊訪問它時,你需要在你的依賴關係數組中放置一個文件路徑,並將相應的變量提供給以下函數。

define(["folder/a-script", "folder/another-script"], function(AScript, AnotherScript) { 
     // In here the scripts are loaded and can be used, but are called by 
     // their relative name in the anonymous function. 
    } 
); 

不管怎樣,也許在某些情況下,仍有必要命名空間的東西,但我認爲在一般情況下,它的價值reading the docs看到,如果你需要。