Backbone View not refreshing even when Collection

2019-08-17 01:22发布

问题:

I have a backbone collection that dynamically takes the URL to fetch results. I then create a view that has the key-up event to capture key input and refresh the collection from the back-end. I have added a listener to my view for collection change but that is not being triggered on my key-up event even though the collection is getting refreshed.

employees.EmployeesCollection = Backbone.Collection.extend({
        url: function() {
        if(this.searchName)
            return serviceUrls.employees_searchByName_url + "/" + this.searchName;
        else
            return serviceUrls.employees_list_url; 
    },
    searchName: null,
    search: function(searchName) {
        this.searchName = searchName;
        this.fetch({
            success: function() {
                console.log("Fetched new collection");
            },
            error: function(collection, response){
                console.log("Something went wrong");
            }
        });
    },    
    parse: function(response, options) {
        return response;
    }
});

employees.EmployeeListView = Backbone.View.extend({
    el: "#employee",
    template : _.template($('#employees_tpl').html()),
    events : {
        "keyup #searchValue": "searchByName"
    },
    initialize: function(options) {
        this.options = options;
        this.listenTo(this.collection, 'change', this.render);
    },
    render: function() {
        var that = this;
        // Only render the page when we have data
        this.collection.fetch().done(function() {
            that.$el.html(that.template({
                collection: that.collection.toJSON()
            }));
        });
        return this; 
    },
    showResults: function(results){
        this.collection = results;
        this.render();
    },
    // Search Employees By Name
    searchByName: _.throttle(function(e) {
        var searchValue = $("#searchValue").val();
        this.collection.search(searchValue);
    }, 500)
});

// Create Employees View, passing it a new Collection of Employees
var employeesView = new employees.EmployeeListView({
    collection: new employees.EmployeesCollection()
});

回答1:

according to documentation. a "change" event is triggered when model attribute is changed. i suggest adding reset:true in the fetch. and change the listening event to reset.

this.collection.fetch({reset:true, 
    success:function(){...},
    error:function(){...}
})

specifically, in your search method:

search: function(searchName) {
    this.searchName = searchName;
    this.fetch({
        success: function() {
            console.log("Fetched new collection");
        },
        error: function(collection, response){
            console.log("Something went wrong");
        },
        reset:true
    });
},   

then in your view, instead of listen to a change event, listen to a reset

this.listenTo(this.collection, 'reset', this.render);