Exp*_* be 4 coffeescript backbone.js
我正在使用骨干和牵线木偶,
我想对我的收藏和渲染视图进行排序.
但奇怪的是发生了什么.
'/ api/note/getList',它返回(并在视图初始化集合时调用它)
[{"id":22,"name":"Test2","isPublic":1},{"id":11,"name":"Test1","isPublic":1},{"id":33,"name":"Test3","isPublic":1}]
Run Code Online (Sandbox Code Playgroud)
这是我的收藏,
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'
Run Code Online (Sandbox Code Playgroud)
和console.log打印
22
22
11
Run Code Online (Sandbox Code Playgroud)
打印'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()
Run Code Online (Sandbox Code Playgroud)
@collection = new NoteCollection()=>我觉得这个运行自动获取.
mu *_*ort 10
问题是你使用绑定函数作为比较器:
comparator : (item) =>
Run Code Online (Sandbox Code Playgroud)
那令人困惑的是Backbone的"比较器需要多少参数"检查.从精细手册:
比较
collection.comparator[...]比较器可以定义为sortBy(传递一个接受单个参数的函数),作为一种排序(传递一个需要两个参数的比较器函数),[...]
如果我们向内看sort,我们会看到:
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
Run Code Online (Sandbox Code Playgroud)
因此,如果comparator是一个带有一个参数(即comparator.length === 1)的函数,那么sortBy将使用并且比较器将获得一个参数; 但是,如果comparator是一个不带一个参数的函数,则使用标准sort,比较器将传递两个参数.
如果你看着comparator被叫,你会发现它有两个参数.怎么会发生这种情况?如果comparator.length不是一个就会发生这种情况.由于CoffeeScript实现的方式,你comparator最终length得到零=>; 例如:
class C
m1: (x) -> x
m2: (x) => x
c = new C
console.log(c.m1.length)
console.log(c.m2.length)
Run Code Online (Sandbox Code Playgroud)
会给你1和0控制台.
演示:http://jsfiddle.net/ambiguous/GAAap/
如果你看一下JavaScript:
class C
m: (x) => x
Run Code Online (Sandbox Code Playgroud)
你会看到使用这个功能
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Run Code Online (Sandbox Code Playgroud)
生成=>方法.请注意return function() { ... }那里?这意味着每种=>方法都声称具有length零.恭喜,我想你已经重新发现了CoffeeScript中的一个错误.
如果您使用标准->方法comparator:
comparator: (item) -> item.id
Run Code Online (Sandbox Code Playgroud)
然后CoffeeScript不会搞砸你comparator的length价值,你的排序将开始有意义.
演示:http://jsfiddle.net/ambiguous/WXDcJ/
看起来流行病已经报告了这个错误:
执行摘要:不要=>用于Backbone收集比较器功能.
| 归档时间: |
|
| 查看次数: |
4258 次 |
| 最近记录: |