3

我正在使用Marionette.CompositeView并且我想根据这两个示例(1)和(2)来了解 serializeData 和 onRender 之间的区别。

根据文档,在应用模板之前在渲染中调用 serializeData,在应用模板之后在渲染中调用 onRender。

我的问题是:
1)为什么示例(1)有效而(2)无效?
2)如果我重置集合,会Marionette.CompositeView重新渲染吗?

请参阅代码中的注释以获取更多详细信息。


(1)

return Marionette.CompositeView.extend({

        initialize: function () {
            this.collection = new MyCollection();
            this.collection.fetch();
        },

        onRender: function () {
            this.collection.length > 0 ? this.$el.show() : this.$el.hide();
           // it returns this.collection.length > 0 
           // differently from serializeData.
        }
});

(2)

return Marionette.CompositeView.extend({

        initialize: function () {
            this.collection = new MyCollection();
            this.collection.fetch();
        },

        serializeData: function () {
            this.collection.length > 0 ? this.$el.show() : this.$el.hide(); 
           // it returns this.collection.length = 0 
           // even if this.collection.length > 0. Why?
        }
});
4

1 回答 1

6

1) As you said, onRender is just a callback function which is called after rendering the view.

serializeData must return a valid JSON object as it's said in the Backbone Marionette documentation :

If you need custom serialization for your data, you can provide a serializeData method on your view. It must return a valid JSON object, as if you had called .toJSON on a model or collection.

Backbone.Marionette.ItemView.extend({
  serializeData: function(){
    return {
      "some attribute": "some value"
    }
  }

});

2) IMO, the answer is yes. In the Backbone Marionette documentation, it's said :

CollectionView: Automatic Rendering

The collection view binds to the "add", "remove" and "reset" events of the collection that is specified.

When the collection for the view is "reset", the view will call render on itself and re-render the entire collection.

When a model is added to the collection, the collection view will render that one model in to the collection of item views.

When a model is removed from a collection (or destroyed / deleted), the collection view will close and remove that model's item view.

于 2012-08-10T10:35:21.043 回答