1

我希望我的合成能够自动呈现一个集合,它已经这样做了。但是,我也希望它为我获取模型并授予对该模型的复合访问权限。

基本上我正在尝试使用下面的一组客户来呈现用户详细信息。

复合视图

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

项目视图

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

1 回答 1

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

这大概是它的样子。如果有疑问,请查看骨干网的来源。

于 2013-10-09T13:49:11.617 回答