木偶复合视图与模型

Marionette CompositeView with a model

本文关键字:模型 视图 复合      更新时间:2023-09-26

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

基本上,我正在尝试使用下面的客户端集合呈现用户详细信息。

复合视图

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?

您可能最好不要从视图中实例化您的集合/模型。

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

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