2011-11-16 80 views
9

我當前使用require.js像這樣工作AMD骨幹型號:如何使用Node.js的具有和AMD(在瀏覽器上require.js)骨幹示範

// models/game.js 
define(['backbone'], 
function(Backbone) { 

    var Game = Backbone.Model.extend({ 
    urlRoot : '/games/' 
    , defaults : { 
     name : null 
    } 
    }); 

    return Game; 
}); 

的AMD /骨幹組織來自this tutorialjrburke's Pull Request for Backbone

我想在Node.js中使用Backbone Model,因爲在不使用AMD的情況下共享Backbone模型和集合在過去運行良好,顯然我是受虐狂。

所以我嘗試了以下(由骨幹MOD靈感):

// models/game.js 
(function(root, factory) { 
    if (typeof exports !== 'undefined') { 
    factory(root, exports, require('backbone')); 
    } 
    else if (typeof define === 'function' && define.amd) { 
    define(['backbone'], function(Backbone, exports) { 
     factory(root, exports, Backbone); 
    }); 
    } 
}(this, function(root, Game, Backbone) { 

    Game = Backbone.Model.extend({ 
    urlRoot : '/games/' 
    , defaults : { 
     name : null 
    } 
    }); 

    return Game; 
})); 

Game現在是不確定的,當我包括在瀏覽器中:

// collections/games.js 
define(['backbone', 'models/game'], 
function(Backbone, Game) { 

    var Games = Backbone.Collection.extend({ 
    model: Game 

    , initialize: function() { 
     console.log(Game) 
     // Game is undefined 
     var game = new Game({ name: 'game1' }); 
    } 
    }); 

    return Games; 
}); 

當我看着CommonJS notes ,恐怕我還不清楚。 如何在瀏覽器中使用與AMD文件相同的骨幹模型文件和Node.js模塊?

對於獎金:是否有比每個文件頂部〜10行更清潔的方式?理想情況下沒有define shim

回答

4

您是否嘗試過在節點上使用AMD方式?

http://requirejs.org/docs/node.html - 如果你想在客戶端和後端都有相同的AMD模塊,可能是最好的解決方案。

相關問題