I’m working in Backbone js and I am trying to populate a model with data using fetch. The problem is that the fetch appears to be working but my model is not populating with data.
A snippet of the code:
Backbone.emulateHTTP = true;
Backbone.emulateJSON = true;
ComponentsModel = Backbone.Model.extend({
initialize : function() {
},
defaults : {
component_id : null
},
urlRoot : "/components/ajax_component",
});
ComponentsView = Backbone.View.extend({
el : $('body'),
events : {
'change #component-selector' : 'changeComponent',
},
initialize : function() {
_.bindAll(this, 'render', 'changeComponent');
this.render();
},
changeComponent : function(e) {
var clickedEl = $(e.currentTarget);
var value = clickedEl.attr("value");
var component = new ComponentsModel({id :value, component_id :value });
component.fetch();
component.toJSON();
alert(component.get('component_name'));
},
render : function() {
},
});
And the JSON being return from the server looks like this:
{"component_id":"1","component_name":"Test Component 1","component_description":"A simple test component","component_required":"","user_id":"1","component_approved":"0","component_price":"0","component_overview":"'"}
The alert is always undefined. Am I missing something?
Fetch is async, that’s why it has
successanderrorcallbacks. So it’s no sure that the data are fetched by the time you try to get the property.Try this: