我试图在 Backbone 应用程序中使用 CommonJS 模块,所以我在 /views/categories/edit.js
中定义了一个框架 Backbone View:
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;
}
});
如果有人能告诉我如何将其转换为 CommonJS 模块以与 Browserify 一起使用,那么我将不胜感激,这将真正帮助我理解如何模块化应用程序的其余部分!谢谢
最佳答案
//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;
评论中的后续问题:
Very much appreciate this! How would you approach: app.Collections.quotesCategories as I house everything under the app namespace? Do I just require the Collection itself?
所以“app”命名空间的想法与模块化/commonjs/browserify/requirejs 相反。您不再需要 app
对象。任何需要创建此集合的新实例的模块只需执行 var QuotesCategories = require('app/collections/quotes-categories');
即可。没有更多的全局变量或命名空间对象。大多数情况下,您的 View 将在其构造函数 options
中获得所需的模型/集合。您的大部分模型将通过对集合调用 fetch
来创建,并且您的大部分集合将由您的路由器实例化。
哦,是的,在这个特定示例中,最好是非 View 代码创建集合并通过构造函数 options.collection
参数将其传递给 View 。但是,如果您决定是,您真的希望您的 View 实例化集合,它不会来自 app
全局命名空间对象,它只会来自 require
调用正如您在评论中所描述的那样。
关于backbone.js - 作为 CommonJS 模块的主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657711/