gpt4 book ai didi

Backbone.js:更新模型,重新排序和重新渲染模型集合

转载 作者:行者123 更新时间:2023-12-04 17:02:50 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个 socket.io 连接,它正在监听后端并获取客户端浏览器保存的模型的更新(它通过 id 检索模型并在模型属性上调用 set)。

我希望对集合进行排序,然后作为一个整体重新渲染,以反射(reflect)由于 set 对模型的任何新排序(大多数示例似乎都围绕重新呈现的单个 View )。实现这一目标的方法是什么?

NB
我已经从示例 todo 应用程序(这是第一个主干应用程序)中逐字提升了一个backbone.js布局。

最佳答案

您可以通过提供 comparator 来实现您想要的方法为您的收藏。

示例:

ModelCollection = Backbone.Collection.extend({
comparator: function(a, b) {
if ( a.get("name") > b.get("name") ) return 1;
if ( a.get("name") < b.get("name") ) return -1;
if ( a.get("name") === b.get("name") ) return 0;
},

initialize: function() {
this.on('change:name', function() { this.sort() }, this);
}
});
comparator在此示例中,您的集合将按 name 升序排序。里面模型的属性。

请注意,更改任何 models 的属性时,您的集合不会自动排序。 .默认情况下,排序仅在创建新模型并将它们添加到集合时发生;但 comparator将由 collection.sort 使用方法。

上面的代码通过设置一个事件监听器来利用这一点,该监听器简单地对任何 change 上的集合进行重新排序。 s 到 name其属性 models .

为了完成图片,我们在 View中设置了一个合适的事件监听器。与集合关联以确保它在任何更改时重新呈现:
CollectionView = Backbone.View.extend({
initialize: function() {
this.collection = new ModelCollection();
this.collection.on('all', function() { this.render() }, this);
},

render: function() {
this.$el.html(this.collection.toJSON());
}
});

就是这样 :)

相关摘录自 Backbone documentation :

By default there is no comparator for a collection. If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in collection.models. A comparator can be defined as a sortBy (pass a function that takes a single argument), as a sort (pass a comparator function that expects two arguments), or as a string indicating the attribute to sort by. [...] Collections with a comparator will not automatically re-sort if you later change model attributes, so you may wish to call sort after changing model attributes that would affect the order.

关于Backbone.js:更新模型,重新排序和重新渲染模型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10265113/

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