繁体   English   中英

骨干视图作为CommonJS模块

[英]Backbone Views as CommonJS modules

我正在尝试在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;
    }

});

如果有人能告诉我如何将其转换为与Browserify一起使用的CommonJS模块,那么我将非常感激,这真的有助于我理解我如何模块化其他应用程序! 谢谢

//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”命名空间的概念与modular / commonjs / browserify / requirejs相反。 您不再需要app对象。 任何需要创建此集合的新实例的模块var QuotesCategories = require('app/collections/quotes-categories'); 这就是全部。 不再有全局变量或命名空间对象。 大多数情况下,您的视图将在其构造函数options获取所需的模型/集合。 大多数模型都是通过调用集合上的fetch来创建的,并且大多数集合都将由路由器实例化。

哦,是的,在这个具体的例子中,如果非视图代码创建集合并通过构造函数options.collection参数将其传递给视图,则可能是最好的。 但是,如果你决定是的,你真的希望你的视图实例化集合,它不会来自app全局命名空间对象,它只会来自你在评论中描述的require调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM