App结构和App.vent.bind

时间:2012-10-18 03:16:54

标签: marionette

我有两个应用程序:

具有链接模型的SrvLinkApp(与服务器的sockjs连接)。 ChatApp chatView视图,ChatEntry模型和ChatCollection

当我收到服务器的msg时,我会触发'chat:server:message',有效负载事件:

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

在我的ChatApp我收听此事件时,将有效负载转换为ChatEntry,然后将其添加到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);
});
});

或者是否有其他方式可以访问该集合?

1 个答案:

答案 0 :(得分:1)

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

就个人而言,我会选择A,因为它会保留模块中的所有内容,并且不会使集合处于打开状态,以便在全局应用程序对象上被破坏或遗忘(内存泄漏)。