Question

I am new to the backbone. I tried to do ajax call in the below manner. And I am not sure how to handle the data from my get request? Here is the code:

//Interacting with the server

var UserModel = Backbone.Model.extend({
    url:'http://api.geonames.org/astergdemJSON?formatted=true&lat=50.01&lng=10.2&username=demo&style=full'
});

var MyView = Backbone.View.extend({
    initialize: function() {
        this.model = new UserModel();
        this.model.fetch();
    },
    render: function() {
        alert('do awesome stuff here');
    }
});
Was it helpful?

Solution

When you make fetch(), Backbone will send an GET ajax request to the endpoint you specifiend on url.

When you call .fetch, the model will trigger a request event, and when you receive it, parse it and set it to the model, the model will trigger a sync event.

If you want to change any data before setting it to the model, override the method parse on you model. It receives the raw data from the GET request and must return what is going to be set to your model.

If you want extra success and error callbacks, pass them in you your fecth({ success: ..., error: ... }). Success callback is triggered after setting and parsing the values to the model and before sync event. Error callback is triggered before error event. Look the documentation for more details. It is not necessary to pass any of those callbacks.

So, it would be something like:

var MyView = Backbone.View.extend({
    initialize: function() {
        this.model = new UserModel();
        this.listenTo(this.model, 'sync', this.render);
        this.model.fetch();
    },
    render: function() {
        alert('My model loaded: ' + this.model.toJSON());
    }
});

And, that's it. Backbone makes almost everything for you.

Hope I've helped.

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