How should backbone.js handle a GET request that returns no results?

Posted by Nyxynyx on Stack Overflow See other posts from Stack Overflow or by Nyxynyx
Published on 2012-06-16T23:51:53Z Indexed on 2012/06/17 9:16 UTC
Read the original article Hit count: 302

I have a number of text input elements that when its values are changed, will trigger a fetch on listingListView's collection listingCollection, which then updates listingListView with the new data via the function listingListView.refreshList as shown below. I am using PHP/Codeigniter to expose a RESTful API.

Problem: Everything works fine if there are results retrieved from the fetch(). However, when the filters results in no result being returned, how should the server side and the client side handle it? Currently Chrome's javascript console displays a 404 error and in the Network tab, the XHR request is highlighted in red. All I want to do in the event of zero results returned, is to blank the listingListView and show a message like (No results returned) and not throw any errors in the javascript console. Thanks!

PHP Code

function listings_get() {
    // Get filters
    $price_min = $this->get('price_min');

    $this->load->model('app_model');
    $results = $this->app_model->get_listings($price_min);

    if($results)
        $this->response($results);
    else 
        $this->response(NULL);
}

JS Code

window.ListingListView = Backbone.View.extend({
    tagName: 'table',

    initialize: function() {
        this.model.bind('reset', this.refreshList, this);
        this.model.bind('add', function(listing) {
            $(this.el).append(new ListingListItemView({ model: listing }).render().el);
        }, this);
    },

    render: function() {
        _.each(this.model.models, function(listing) {
            $(this.el).append(new ListingListItemView({ model: listing }).render().el);
        }, this);
        return this;
    },

    close: function() {
        $(this.el).unbind();
        $(this.el).empty();
    },

    refreshList: function() {
        $(this.el).empty();
        this.render();
    }
});

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery