gpt4 book ai didi

backbone.js - Backbone 收集比较器

转载 作者:行者123 更新时间:2023-12-04 22:47:10 26 4
gpt4 key购买 nike

我正在使用 Backbone 和木偶,

我想对我的收藏和渲染 View 进行排序。

但是发生了一些奇怪的事情。

'/api/note/getList' ,它返回(并在集合被 View 初始化时调用)

[{"id":22,"name":"Test2","isPublic":1},{"id":11,"name":"Test1","isPublic":1},{"id":33,"name":"Test3","isPublic":1}]

这是我的收藏,
define [
'models/Note'
],
(Note) ->
class NoteCollection extends Backbone.Collection

model : Note
url : '/api/note/getList'

comparator : (item) =>
console.log item.get 'id'
return item.get 'id'

和 console.log 打印
22
22
11

打印'22'两次?它也没有排序。

我应该怎么做才能对集合进行排序?

[编辑]

这是我初始化集合的 compisteView
define [    
'hbs!./noteCollection_tpl'
'./noteItemView'
'collections/NoteCollection'
],
(noteCollection_tpl, noteItemView, NoteCollection) ->
class NoteCollectionView extends Backbone.Marionette.CompositeView
template : noteCollection_tpl
itemView : noteItemView
itemViewContainer : '.noteListContainer'
className : 'noteWrap'

initialize : (options) ->
@collection = new NoteCollection()

@collection = new NoteCollection() => 我认为这个运行会自动获取。

最佳答案

问题是您使用绑定(bind)函数作为比较器:

comparator : (item) =>

这使 Backbone 的“比较器接受多少参数”检查感到困惑。来自 fine manual :

comparator collection.comparator

[...] 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), [...]



如果我们看里面 sort ,我们看到这个:
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}

所以如果 comparator是一个接受一个参数的函数(即 comparator.length === 1 ),然后是 sortBy将被使用,比较器将得到一个参数;但是,如果 comparator是一个不接受一个参数的函数,然后是标准 sort被使用并且比较器将被传递两个参数。

如果你看你的 comparator被调用,你会看到它得到 两个 论据。怎么会这样?如果 comparator.length 会发生这种情况不是一个。您的 comparatorlength 结尾由于 CoffeeScript 实现的方式而为零, => ;例如:
class C
m1: (x) -> x
m2: (x) => x

c = new C
console.log(c.m1.length)
console.log(c.m2.length)

会给你 10在控制台中。

演示 : http://jsfiddle.net/ambiguous/GAAap/

如果您为此查看 JavaScript:
class C
m: (x) => x

你会看到 this function is used
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

生成 =>方法。注意 return function() { ... }在那里?这意味着每个 =>方法将声称具有 length为零。恭喜,我认为您重新发现了 CoffeeScript 中的一个错误。

如果您使用标准 ->您的 comparator 的方法:
comparator: (item) -> item.id

那么 CoffeeScript 不会搞砸你的 comparatorlength值(value)和你的排序将开始有意义。

演示 : http://jsfiddle.net/ambiguous/WXDcJ/

看起来像 epidemian已经报告了这个错误:

https://github.com/jashkenas/coffee-script/pull/2872



执行摘要 : 不要使用 =>用于 Backbone 收集比较器功能。

关于backbone.js - Backbone 收集比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20127637/

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