Question

I'm working out my first backbone.js app and have run into a bit of a wall. Perhaps someone can help me past this hurdle (gap in my understanding). What I want/need to do is to return the collection data to my router, so I can bind it to a Kendo UI Grid, but I'm not seeing any of the search results in my collection... I figure I must be missing something fundamental, but I'm not sure what it is.

Here is what I have so far:

    ES.Router = Backbone.Router.extend({routes: {
            '': 'search',
            'search': 'search',
            'results': 'results'
        },
        results: function() {
            var resultsData = new ES.Results();
            var boo = resultsData.fetch({
                    data: JSON.stringify({"query":"myquery"}),
                    type: 'POST',
                    contentType: 'application/json'
                    });
            console.log(boo);
        }});

    ES.Result = Backbone.Model.extend();

    ES.Results = Backbone.Collection.extend({   
        model: ES.Result,
        url: '/search/query'
        });
Was it helpful?

Solution

There are a few issues here:

  1. A fetch should be a GET, not a POST, because a fetch should not save or modify anything
  2. Maybe just a personal preference, but I'd url as a function, so as to avoid trying to modify the AJAX request options manually.
  3. The fetch call will always be asynchronous, so you need to either add a success callback in the options hash, or add a listener to the collection's reset event

I'd write the collection like this:

ES.Results = Backbone.Collection.extend({   
    initialize: function() {
        this.query = "test";
    },
    model: ES.Result,
    url: function() {
        return '/search/query?query=' + this.query;
    }
});

Then set the search when you create the collection:

var resultsData = new ES.Results();
resultsData.query = "soccer";

And use success and/or the on("reset") event to handle the result:

resultsData.on("reset", function(collection) {
    console.log(collection);
});

console.log("Fetching....");
resultsData.fetch({
    success: function(collection, response) {
        console.log("Got data!" + collection.length);
    },
    error: function(collection, response) {
        console.log("Error: " + response.responseText);
    }
});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top