2013-07-15 89 views
2

我试图让我的头周围采用主干应用程序中CommonJS的模块,所以我必须在/views/categories/edit.js定义的骨架骨干查看:骨干视图作为CommonJS的模块

app.Views.quoteCategoriesEdit = app.Ui.ModalView.extend({ 

    className: '', 

    template: JST["templates/quotes/categories/quote-categories-edit.html"], 
    events: { 
     'click [data-key="save"]': 'save', 
     'click [data-key="cancel"]': 'cancel' 
    }, 
    initialize: function (options) { 
     var that = this; 
     _.bindAll(this, 'save', 'cancel'); 
     app.Collections.quotesCategories.on('change add', function() { 
      that.remove(); 
     }); 
    }, 

    render: function() { 
     var that = this; 
     // boilerplate render code 
     return this; 
    } 

}); 

如果有人能告诉我如何我可以将它转换成与Browserify一起使用的CommonJS模块,那么我会非常感激,它会帮助我理解我如何去模块化应用程序的其余部分!从评论感谢

回答

7
//once you get things into folders/files, this path may change 
//but for now I'm assuming all your views will live in the same directory 
var ModalView = require('./modal-view'); 

var QuoteCategoriesEdit = ModalView.extend({ 

    className: '', 

    template: JST["templates/quotes/categories/quote-categories-edit.html"], 
    events: { 
     'click [data-key="save"]': 'save', 
     'click [data-key="cancel"]': 'cancel' 
    }, 
    initialize: function (options) { 
     var that = this; 
     _.bindAll(this, 'save', 'cancel'); 
     app.Collections.quotesCategories.on('change add', function() { 
      that.remove(); 
     }); 
    }, 

    render: function() { 
     var that = this; 
     // boilerplate render code 
     return this; 
    } 

}); 
//Simplest convention is just 1-class-per-module 
//Just export the constructor function 
module.exports = QuoteCategoriesEdit; 

后续问题:

很欣赏这个!你将如何处理:app.Collections.quotesCategories,因为我把应用程序命名空间下的所有东西都放在了一起?我只需要收集本身?

所以“app”命名空间的概念与模块化/ commonjs/browserify/requirejs相反。你不再需要一个app对象。任何需要创建这个集合的新实例的模块只需要做var QuotesCategories = require('app/collections/quotes-categories');即可。没有更多的全局或命名空间对象。大多数情况下,您的视图将在构造函数options中获得他们需要的模型/集合。大多数模型将通过在集合上调用fetch而创建,并且大多数集合将由您的路由器实例化。

哦,是的,在这个特定的例子中,最好是非视图代码创建集合并通过构造函数options.collection将其传递给视图。但是,如果您确定是的,您确实希望您的视图实例化集合,它不会来自全局名称空间对象,它只会来自require调用,如您在评论中所述。

+0

非常感谢这!你将如何处理:'app.Collections.quotesCategories',因为我把'app'命名空间下的所有东西都放在了一起?我只需要'收藏'本身? – benhowdle89

+0

请看我的更新回答 –

+0

非常非常有帮助,非常感谢!当我搜索到Backbone和CommonJS时,并没有那么多,更多Backbone和AMD! – benhowdle89