gpt4 book ai didi

javascript - CompositeView 中的序列化数据

转载 作者:行者123 更新时间:2023-12-02 22:36:56 26 4
gpt4 key购买 nike

我需要向 listView.template 传递一个值,以便了解有关 collection.length 的模板。
我认为一种选择是重新定义 serializeData 方法以便以这种方式传递参数。

var ListView = Marionette.CompositeView.extend({

initialize: function () {
this.collection.on('reset', this.serializeData, this);
this.collection.on('remove', this.serializeData, this);
this.collection.on('add', this.serializeData, this);
},

serializeData: function () {
console.log(this.collection.length);
return {
has_tasks: this.collection.length > 0
};
},

// other codes
});

当我启动 app 时,collection 尚未获取,因此:

1.a) collection.legth = 0
2.b) 模板按预期得到 has_tasks = false

2.a) 获取 collection.length > 0 后,
2.b) serializeData 被调用,因此它将 has_tasks = true,
2.c) 模板似乎没有呈现,因为它维护了 has_tasks = false

因为 2.c 有什么想法吗?

最佳答案

Latest Marionette 通过在 View 上调用可选的 templateHelpers 来为 View 提供额外的上下文,从而解决了这个问题。此外,您的事件绑定(bind)对 Marionette 不友好,因为它不会在卸载 View 时正确地自动取消绑定(bind)。所以在你看来你需要做的就是:

var ListView = Marionette.CompositeView.extend({

initialize: function () {
this.bindTo(this.collection, "add", this.render, this);
this.bindTo(this.collection, "remove", this.render, this);
this.bindTo(this.collection, "reset", this.render, this);
},

templateHelpers: function () {
console.log(this.collection.length);
return {
has_tasks: this.collection.length > 0
};
},

// other codes
});

但是请注意,您可能不想在每次添加或删除项目时都重新呈现整个 View 和所有子元素。更好的方法是只更新显示的计数。例如:

var ListView = Marionette.CompositeView.extend({

initialize: function () {
this.bindTo(this.collection, "add", this.updateCount, this);
this.bindTo(this.collection, "remove", this.updateCount, this);
this.bindTo(this.collection, "reset", this.updateCount, this);
},

updateCount: function() {
this.$('.count_span').html(this.collection.length);
},

// other codes
});

关于javascript - CompositeView 中的序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11328574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com