0

我有两个应用程序:

SrvLinkApp具有链接模型(sockjs与服务器的连接)的A。具有视图、ChatApp模型和.chatViewChatEntryChatCollection

当我收到来自服务器的消息时,我触发了一个“聊天:服务器:消息”,有效负载事件:

App.vent.trigger('chat:server:message', payload)

在我的ChatApp我监听这个事件,将有效负载转换为 aChatEntry然后将其添加到ChatCollectionChatView.

我应该在哪里添加绑定?我只有在初始化部分对集合的引用:

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);
});
});

还是有其他方法可以访问该集合?

4

1 回答 1

1

我不认为这两个都不好。我在不同的时间使用这两种想法。这在很大程度上取决于您的应用程序中的其他情况,处理多个集合的可能性等。

就个人而言,我会选择 A,因为它将所有内容都保留在模块中,并且不会让集合在全局 app 对象上被破坏或遗忘(内存泄漏)。

于 2012-10-21T03:00:56.040 回答