骨干收集和视图排序

时间:2013-11-22 16:46:08

标签: backbone.js coffeescript

我在我的集​​合中设置'comparator'方法,以便我可以在集合中对列表进行排序。 但它不会影响观看。

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

[{"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'

        initialize: () =>
            _.bindAll @
            @.on 'sort', @onSort

        comparator : (item) ->
            id = item.get 'id'
            return id * -1

        onSort: () =>
            @.each (model) =>
                console.log model.get 'id'

onSort方法打印,

11
22
33

正确,但在视图中,它显示

22
11
33

这是我的观点,

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() 

我是否需要重新渲染视图?如果是这样,我怎样才能在加载url并将所有列表收集到收集后捕获(what)事件?

请告知我做错了什么。

1 个答案:

答案 0 :(得分:0)

需要在对集合进行排序时进行渲染。

initialize : (options) ->
    @collection = new NoteCollection()
    @collection.on 'sort', () =>
        @render()

Aww,更好地使用' listenTo '因为,

当视图被销毁时,listenTo调用将自动删除事件处理程序。这可以防止内存泄漏和僵尸事件侦听器。

我相信,使用木偶会解决这个僵尸事件听众。

感谢Yurui Ray Zhang。