我使用 BackboneJS 开发大型企业应用程序。应用程序中的一个页面是通过 REST 使用多个子系统调用构建的。如何确保已调用加载页面所需的所有服务并且已完成模板绑定?
例如,我有一个MasterView
, 负责处理collection.fetch()
每个子视图,就像这样。
myApp.views.MasterView = Backbone.View.extend({
initialize: function(params) {
var self = this;
this.collection.fetch({
success: function(resp) {
self.collection.bind("reset", self.render(), self);
},
error: function(xhr, xhrStatus) {
// push error message, in case of fetch fails.
}
});
},
render: function() {
var self = this;
this.collection.each(function(model) {
if (model.get('authorize') && model.get('status') === "success" && model.get('data').length > 0) {
self.bindTemplate(model.get('data')[0]);
}
});
}
});
我为页面设置了一个视图,它负责呈现另外两个视图 CustomerInfo 和 CustomerAccounts。景色是这样的。
myApp.views.CustomerView = Backbone.View.extend({
initialize: function() {
var customerInfo = new myApp.collection.CustomerInfo();
new myApp.views.CustomerInfo({el: $("#infoContainer"), collection: customerInfo});
var customerAccount = new myApp.collection.CustomerAccount();
new myApp.views.CustomerAccount({el: $("#accountContainer"), collection: customerAccount});
}
});
而 CustomerInfo 和 CustomerAccount 视图,看起来像这样,
myApp.views.CustomerInfo = myApp.views.MasterView.extend({
initialize: function() {
var self = this;
myApp.views.MasterView.prototype.initialize.call(self, {
qParam1: "qparam1",
qParam2: "qparam2"
});
},
render: function() {
var self = this;
self.template = _.template(myApp.Templates.get("customer-page/customer-info"));
myApp.views.MasterView.prototype.render.apply(self);
},
bindTemplate: function(data) {
var self = this;
$(self.el).html(self.template({"info": data}));
}
});
myApp.views.CustomerAccounts = myApp.views.MasterView.extend({
initialize: function() {
var self = this;
myApp.views.MasterView.prototype.initialize.call(self, {
qParam1: "qparam1"
});
},
render: function() {
var self = this;
self.template = _.template(myApp.Templates.get("customer-page/customer-accounts"));
myApp.views.MasterView.prototype.render.apply(self);
},
bindTemplate: function(data) {
var self = this;
$(self.el).html(self.template({"accounts": data}));
}
});
我想知道是否有任何方法可以从myApp.views.CustomerView
视图中知道CustomerInfo
并CustomerAccounts
完成渲染?我在这里遇到的主要问题是CustomerInfo
视图加载速度很快,但CustomerAccount
视图需要一些时间才能加载。因此,当两个视图都在 DOM 上准备好时,我需要一次显示页面。