Browserify + Backbone.js"ApplicationState"共享模块

Fab*_* B. 3 javascript commonjs node.js backbone.js browserify

我不明白如何使用browserify在不同视图之间共享某种"单例"应用程序状态保持对象模型.书籍和教程通常使用全局命名空间,例如:

var app = app || {};
Run Code Online (Sandbox Code Playgroud)

我有一个简单的示例应用程序,其中包括:

app.js

var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;

var MenuView = require('./views/MenuView');
var ContainerView = require('./views/ContainerView');

new MenuView();
new ContainerView();
Run Code Online (Sandbox Code Playgroud)

MenuView.js

var Backbone = require('backbone');
var ApplicationState = require('../models/ApplicationState');

module.exports = Backbone.View.extend({
    el: '#menuView', 
    events: {
        'click .menuLink': 'changePage'
    },
    changePage: function(event) {
        event.preventDefault();
        var viewName = $(event.target).attr('data-view');
        ApplicationState.set('currentView',viewName);
    }
});
Run Code Online (Sandbox Code Playgroud)

ContainerView.js

var Backbone = require('backbone');
var ApplicationState = require('../models/ApplicationState');

module.exports = Backbone.View.extend({
    el: '#containerView', 
    initialize: function() {
        this.listenTo( ApplicationState, 'change', this.render );   
        this.render();
    },
    render: function() {
        this.$el.html( ApplicationState.get('currentView') );
    },
    close: function() {
        this.stopListening();
    }
});
Run Code Online (Sandbox Code Playgroud)

这似乎使用这种方法:

ApplicationState.js var Backbone = require('backbone');

var ApplicationState = Backbone.Model.extend({
    defaults: {
        currentView: 'TransactionListView'
    }
});

module.exports = new ApplicationState();
Run Code Online (Sandbox Code Playgroud)

ApplicationState模块是否真的只创建一次(缓存)?或者是否存在重新创建/重置模块的风险?

我的用例的最佳做法是什么?非常感谢.

Mar*_*all 5

是的,在您给出的示例中只有一个ApplicationState.module.exports =一旦js文件运行,Browserify就会执行以下任何操作,然后任何需要该文件的内容都会传递对结果的引用.

但是,通常更好的做法是避免在视图之间以这种方式共享状态,而是使用委托给子视图的父视图.有很多方法可以设置它.有关组织骨干应用程序的最佳实践的想法,请查看此演讲:https://www.youtube.com/watch?v = Lm05e5sJaE8

对于您给出的示例,我会高度考虑使用Backbone的路由器.在您的示例中,您有一个更改"主"视图的导航.Backbone.Router拦截导航并根据调用您的view方法的指定路径进行检查.例如:

router.js

module.exports = Backbone.Router.extend({
    initialize: function(options){
        this.ContainerView = new ContainerView();
    },
    routes: {
        'transactions': 'showTransactionListView',
        'transaction/:id': 'showTransactionDetailView'
    },
    showTransactionListView: function() {
        this.ContainerView.render('TransactionListView');
    },
    showTransactionDetailView: function(id) {
        this.ContainerView.render('TransactionDetailView', id);
    }
});
Run Code Online (Sandbox Code Playgroud)

然后任何链接#transations(或者只是transactions你正在使用Backbone History)都会调用你的ContainerView.render('TransactionListView').并且,作为奖励,如果您重新加载页面,您仍然会看到TransactionListView.

其他说明:

  • 您需要确保在替换它们时(通过调用.remove()它们)丢弃旧视图,以避免内存泄漏. 进一步阅读
  • 您可以为路由器添加一些灵活性,并使用控制器模式使用这个漂亮的插件呈现子视图