Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Database with Backbone Collection

Tags:

backbone.js

I need to query the database using a backbone collection. I have no idea how to do this. I assume that I need to set a url somewhere, but I don't know where that is. I apologize that this must be a very basic question, but I took a backbone course on CodeSchool.com and I still don't know where to begin.

This is the code that I have for the collection:

var NewCollection = Backbone.Collection.extend({

    //INITIALIZE

    initialize: function(){

        _.bindAll(this); 

        // Bind global events

        global_event_hub.bind('refresh_collection', this.on_request_refresh_collection);

    } 

    // On refresh collection event

    on_request_refresh_collection: function(query_args){

        // This is where I am lost. I do not know how to take the "query_args"

        //   and use them to query the server and refresh the collection <------

    } 

})
like image 655
Jaime Rivera Avatar asked Apr 19 '26 08:04

Jaime Rivera


1 Answers

The simple answer is you would define a URL property or function to your Backbone.Collection like so:

initialize: function() {
    // Code
},
on_request_refresh_collection: function() {
    // Code
},
url: 'myURL/whateverItIs'

OR

url: function() {
    return 'moreComplex/' + whateverID + '/orWhatever/' + youWant;
}

After your URL function is defined all you would have to do is run a fetch() on that collection instance and it will use whatever you set your URL to.

EDIT ------- Making Collection Queries

So once you set the URL you can easily make queries using the native fetch() method.

fetch() takes an option called data:{} where you can send to the server your query arguments like so:

userCollection.fetch({
    data: {
        queryTerms: arrayOfTerms[],  // Or whatever you want to send
        page: userCollection.page,  // Pagination data
        length: userCollection.length  // How many per page data
        // The above are all just examples. You can make up your own data.properties
    },
    success: function() {
    },
    error: function() {
    }
});

Then on your sever end you'd just want to make sure to get the parameters of your request and voila.

like image 74
jmk2142 Avatar answered Apr 25 '26 01:04

jmk2142



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!