骨干模型(集合)更改事件不会触发

时间:2014-08-14 13:30:14

标签: javascript backbone.js

任何人都可以向我解释为什么更改事件永远不会在我的代码中触发吗?之前曾提出过类似的问题,但对我没有帮助。我想我的代码中有一个普遍的错误,我没有看到。

item = Backbone.Model.extend({});
itemCollection = Backbone.Collection.extend({model:item, url:"/get.json/data?query=getcol"});

search=Backbone.View.extend({
    el: $("#searchView"),
         events: { 
        'keypress #search_query' : 'lookup', 
        'click #search_button' : 'lookup', 

    },
    initialize: function() {
        this.model = new itemCollection;
        this.model.on("change", this.render, this);     
    }, 
    render: function() { 
        now=new Date().getTime(); /*used to make render() calls visible*/
        json = JSON.stringify(this.model);
        $("#searchResults").html(json + " " + now); 
    }, 
    lookup: function() { 
        this.model.url = "/get.json/data?query=" + $("#search_query").val();
        this.model.fetch();

    }
});
searchview = new search;

(路径“/get.json/data?query=”是正确的。)

1 个答案:

答案 0 :(得分:0)

提取集合时,会触发sync事件。所以改变

  

model.on("更改",this.render,this)

  

model.on(" sync",this.render,this)

为清晰起见,在代码中将this.model重命名为this.collection也是个不错的主意。另请考虑使用listenTo事件,以便在删除视图时清除事件。

this.listenTo(this.collection, "sync", this.render, this)