骨干收集只会触发解析或重置,我想我需要两者

时间:2013-03-22 02:53:29

标签: javascript backbone.js

这是我的问题

我有一个非常简单的骨干集合为我获取一些数据。一切都很好,这样:

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),
    parse:function(response) {
        console.log('parse called');
        return response.data;

    },
    initialize : function(){
        _.bindAll(this, 'reset', 'parse');
    }
});

当调用fetch时,会按预期将解析日志解析到控制台。

但是在那之后我想监听重置事件,这样我就可以使用该集合来填充bootstrap typeahead输入的源数据。所以我这样做了:

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),
    parse:function(response) {
        console.log('parse called');
        console.log(response);
        return response.data;

    },
    reset:function(){
        console.log("change fired");
        $('.dealership_typeahead').typeahead({source:this.pluck('user_name')});
        return true;
    },
    initialize : function(){
        _.bindAll(this, 'reset', 'parse');
    }
});

现在解析事件永远不会被触发,集合不会填充我无法弄清楚原因。

非常感谢任何见解,谢谢。

1 个答案:

答案 0 :(得分:5)

您没有使用该代码与reset事件挂钩。您将覆盖默认的Backbone.Collection reset method(您不希望这样做)。

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),

    initialize: function(models, options){
        this.on('reset', this.doStuff, this);
    },
    parse:function(response) {
        // you DO want to override the default parse method
        return response.data;
    },
    // don't call this method `reset` :)
    doStuff:function(){
        // do something now that collection is fetched
    }
});

我认为你在监听Backbone事件时让_.bindAll感到困惑。 bindAll做了不同的事情,你不需要它。