编程语言
首页 > 编程语言> > javascript – Marionette.CompositeView中serializeData和onRender之间的区别

javascript – Marionette.CompositeView中serializeData和onRender之间的区别

作者:互联网

我正在使用Marionette.CompositeView,我想了解serializeData和onRender之间的区别
基于这两个例子(1)和(2).

根据文档,在应用模板之前在渲染中调用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?
        }
});

解决方法:

1)正如你所说,onRender只是一个回调函数,在渲染视图后调用.

serializeData必须返回一个有效的JSON对象,如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,答案是肯定的.在Backbone Marionette documentation,它说:

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.

标签:javascript,backbone-js,marionette
来源: https://codeday.me/bug/20190826/1727422.html