我不明白如何使用browserify在不同視圖之間共享某種「單例」應用程序狀態持有對象模型。 書籍和教程經常使用全局命名空間,如:Browserify + Backbone.js「ApplicationState」共享模塊
var app = app || {};
我有一個簡單的例子應用程序,它包括:
MenuView.js
app.js
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var MenuView = require('./views/MenuView');
var ContainerView = require('./views/ContainerView');
new MenuView();
new ContainerView();
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);
}
});
個
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();
}
});
這似乎用這種方式工作:
ApplicationState.js VAR骨幹=需要( '骨幹');
var ApplicationState = Backbone.Model.extend({
defaults: {
currentView: 'TransactionListView'
}
});
module.exports = new ApplicationState();
ApplicationState模塊是否真的只創建一次(緩存)? 還是有重新創建/重置模塊的風險?
我用例的最佳實踐是什麼?萬分感謝。
我想這是好的,你可以檢查多少ApplicationState的情況下,將被創建,加入console.count( 'Application State')在ApplicationState.js文件中並在控制檯中查看輸出。 。 – 2014-08-28 21:25:16
'這$ el.html(ApplicationState.get( 'currentView'));'也許應該是'這$ el.html(ApplicationState.get( 'currentView')$ EL);' – 2014-08-29 02:46:20