2013-10-09 37 views
1

我想讓我的組合自動渲染一個集合,它已經完成了。不過,我也想讓它爲我獲取一個模型,併爲該模型提供組合訪問權限。Marionette CompositeView與模型

基本上我試圖呈現用戶的細節與下面的客戶端集合。

CompositeView中

define([ 
    "marionette", 
    "text!app/templates/user/view-clients/collection.html", 
    "app/collections/users/clients", 
    "app/views/user/view-clients/item", 
    'app/models/user' 
], 
    function(Marionette, Template, Collection, Row, Model) { 
    "use strict" 
    return Backbone.Marionette.CompositeView.extend({ 
     template: Template, 
     itemView: Row, 
     itemViewContainer: "#stage-user-clients", 
     collectionEvents: { 
     'sync': 'hideLoading' 
     }, 
     initialize: function (options) { 
     this.showLoading() 

     this.model = new Model({_id: options.id}) 
     this.model.fetch() 

     this.collection = new Collection() 
     this.collection.queryParams = {_id: options.id} 

     return this.collection.fetch() 
     }, 
     showLoading: function() { 
     this.$el.addClass('loading') 
     }, 
     hideLoading: function() { 
     this.$el.removeClass('loading') 
     } 
    }) 
    }) 

ItemView控件

define(["marionette", "text!app/templates/user/view-clients/item.html"], function(Marionette, Template) { 
    "use strict" 
    return Backbone.Marionette.ItemView.extend({ 
    template: Template, 
    tagName: "li" 
    }) 
}) 

請問我需要基本管理的渲染方法自己或爲模型創建一個單獨的視圖和手動綁定,爲一個id複合模板裏面?

回答

4

你可能最好不要在你的視圖中實例化你的集合/模型。

var MyCompositeView = Backbone.Marionette.CompositeView.extend({ 
    initialize: function() { 
     // The collection is already bound, so we take care only of the model 
     // Both will be rendered on model change, though 
     this.listenTo(this.model, 'change', this.render, this); 

     // If you want to rerender the model only, use this instead : 
     this.listenTo(this.model, 'change', function(){ 
      this.$el.html(this.renderModel()); 
     }, this); 
    } 
    ... 
}); 

var myCollection = new Collection({url: '/collection/'}); 
var myModel = new Model({url: '/model/', id: 1}); 

var myCompView = new MyCompositeView({model: myModel, collection: myCollection}); 

myModel.fetch(); 
myCollection.fetch({reset: true}); 

這大致是它的樣子。如有疑問,請查看骨幹的來源。

+0

謝謝。我決定使用佈局,因爲它有點混亂。 – azz0r

+0

不客氣。我竭盡全力回答你問的問題。 – thibauts

相關問題