Marionette.js ItemView - 将子视图放在区域中

Den*_*nis 7 javascript backbone.js marionette

我有以下ItemView模板,其中填充了客户数据(firstName,lastName),我想CollectionView在div中添加一个.addresses.

模板

<script type="text/html" id="template-customer-details">
    <h4><%= firstName %> <%= lastName %></h4>
    <button class="edit">Edit</button>
    <h5>Addresses</h5>
    <div class="addresses">...</div>
</script>
Run Code Online (Sandbox Code Playgroud)

布局

Layout.Details = Backbone.Marionette.ItemView.extend({
    template: '#template-customer-details',

    regions: {
        addresses: ".addresses"
    },

    serializeData: function () {
        return this.model.attributes;
    },

    initialize: function () {

        this.addressList = new App.Models.AddressList();

        // Error!
        this.regions.addresses.show(this.addressList);

        this.bindTo(this, "render", this.$el.refresh, this.$el);
        this.model.bind("change", this.render.bind(this));
    }
});
Run Code Online (Sandbox Code Playgroud)

我收到错误"Uncaught TypeError:Object .addresses没有方法'show'."

我必须等到视图加载?

obm*_*arg 10

我觉得你有点困惑.An ItemViewregions属性没有任何作用(你可能会想到这个Application类),所以当你试着调用this.regions.addresses.show它时就像调用一样".addresses".show.

我想你可能想要CompositeView在这种情况下使用a ,因为它结合了ItemView(你可以用于你的客户数据)和CollectionView你可以用于你的AddressList.您还需要ItemView为地址定义单独的(因为CollectionView只是ItemView为集合中的每个项创建一个).

有点像这样的东西(我没有测试过,所以可能不完全正确):

AddressView = Backbone.Marionette.ItemView.extend({
    template: '#addressTemplate'
});

Layout.Details = Backbone.Marionette.CompositeView.extend({
    template: '#template-customer-details',
    itemView: AddressView,
    itemViewContainer: '.addresses'
});

// Then create your view something like this:
new Layout.Details({
  model: new App.Models.CustomerDetails(),
  collection: new App.Models.AddressList()
});
Run Code Online (Sandbox Code Playgroud)

我也认为你不需要像你的例子那样专门绑定更改和渲染事件,因为marionette通常会处理它(与你的serializeData的实现相同,看起来它与默认实现的模糊相同)