我有两个应用程序:
SrvLinkApp
具有链接模型(sockjs
与服务器的连接)的A。具有视图、ChatApp
模型和.chatView
ChatEntry
ChatCollection
当我收到来自服务器的消息时,我触发了一个“聊天:服务器:消息”,有效负载事件:
App.vent.trigger('chat:server:message', payload)
在我的ChatApp
我监听这个事件,将有效负载转换为 aChatEntry
然后将其添加到ChatCollection
被ChatView
.
我应该在哪里添加绑定?我只有在初始化部分对集合的引用:
App.vent.bind("chat:server:msg", function(msg) {})
A计划
Foo.module("ChatApp", function(ChatApp, App, Backbone, Marionette, $, _) {
App.addRegions({
chatRegion: "#chat-region",
});
MsgEntry = Backbone.Model.extend({});
MsgCollection = Backbone.Collection.extend({
model: MsgEntry
})
MsgView = Backbone.Marionette.ItemView.extend({
template: '#chat-entry-template',
});
MsgListView = Backbone.Marionette.CompositeView.extend({
itemView: MsgView,
itemViewContainer: "#chat-messages",
template: "#chat",
....
});
ChatApp.addInitializer(function() {
var msgCollection = new MsgCollection();
var msgListView = new MsgListView({collection: msgCollection});
// render and display the view
App.chatRegion.show(msgListView);
// App Events listeners
// --------------------
// New chat message from server
App.vent.bind("chat:server:msg", function(msg) {
// create an entry and add it to our collection
console.log(msgCollection);
});
});
});
或B 计划
Foo.module("ChatApp", function(ChatApp, App, Backbone, Marionette, $, _) {
App.addRegions({
chatRegion: "#chat-region",
});
// App Events listeners
// --------------------
// New chat message from server
App.vent.bind("chat:server:msg", function(msg) {
// create an entry and add it to our collection
console.log(ChatApp.msgCollection);
});
MsgEntry = Backbone.Model.extend({});
MsgCollection = Backbone.Collection.extend({
model: MsgEntry
})
MsgView = Backbone.Marionette.ItemView.extend({
template: '#chat-entry-template',
});
MsgListView = Backbone.Marionette.CompositeView.extend({
itemView: MsgView,
itemViewContainer: "#chat-messages",
template: "#chat",
....
});
ChatApp.addInitializer(function() {
var msgCollection = new MsgCollection();
var msgListView = new MsgListView({collection: msgCollection});
// HERE //
ChatApp.msgCollection = msgCollection;
// END HERE //
App.chatRegion.show(msgListView);
});
});
还是有其他方法可以访问该集合?