I am using a model to fetch location data from a service using POST. However I am struggling to get the view to listen to that model when it finally receives a response.
Note I have overriden some model methods to fit the service I am using.
Model code
define([
'underscore',
'backbone',
], function (_, Backbone)
{
'use strict';
//model class declaration
var LocationsModel = Backbone.Model.extend({
locations: null, //this attribute stores the json response
//url for http post to get location data
url: '/testserver/getLocationData',
/**
@name constructor
@method initialise
**/
initialize: function ()
{
console.log("Location Model - Initialize");
this.fetchLocationData();
},
/**
@name fetchLocationData
@method fetchLocationData
@summary retrieves bulding/location data from service, overriden fetch function to use POST
**/
fetchLocationData: function ()
{
console.log("Location Model - Fetching Building/Location data from EAS");
this.fetch({
data: JSON.stringify({ "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "" }), //refactor this - string literals which are static currently
type: "POST",
contentType: "application/json",
async : false, //this is bad but it is the only way I can get it to work
at the moment
reset: true //tried adding reset parameter but no luck
});
},
/**
@name parse
@method parse
@summary parse is a method inside backbone that can be overridden, in this override we set a model attribute to the JSOn response
**/
parse: function (response, xhr)
{
console.log("Location Model - Parsing response from EAS");
this.attributes = { "true": true }; //tried adding an attribute value to trigger "change:true"
this.locations = response;
//do other stuff
},
});
return LocationsModel;
});
In the view initialiser I have tried the following binds and listen to on the model however they don't seem to trigger after a response.
View code
model : new LocationModel(),
initialize: function ()
{
console.log("Filter View - Initialize");
this.render();
this.listenTo(this.model, 'change', this.render); //this only fires at the start when the model is initialised
this.model.on('change', this.render, this); //same as above
this.listenTo(this.model, 'reset', this.render); //not fired at all
},
For a collection it was fairly simple to listen to any changes that happened, however it seems to be a different ball game for Backbone models.
TLDR, how can I get the view to listen to a model successfull fetch request?
The
sync
event is the one you want tolistenTo
. It gets fired once afetch
has completed successfully. This line in the Backbone source is the culprit: Backbone source, line 578.Your code should now look something like this:
View code
Here's a fiddle which shows your code working. I used httpbin to mock the POST request. You can also remove the
async: false
parameter in the fetch request now :) (I've removed it in the fiddle example).