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 : {
ponent_id : null
},
urlRoot : "/ponents/ajax_ponent",
});
ComponentsView = Backbone.View.extend({
el : $('body'),
events : {
'change #ponent-selector' : 'changeComponent',
},
initialize : function() {
_.bindAll(this, 'render', 'changeComponent');
this.render();
},
changeComponent : function(e) {
var clickedEl = $(e.currentTarget);
var value = clickedEl.attr("value");
var ponent = new ComponentsModel({id :value, ponent_id :value });
ponent.fetch();
ponent.toJSON();
alert(ponent.get('ponent_name'));
},
render : function() {
},
});
And the JSON being return from the server looks like this:
{"ponent_id":"1","ponent_name":"Test Component 1","ponent_description":"A simple test ponent","ponent_required":"","user_id":"1","ponent_approved":"0","ponent_price":"0","ponent_overview":"'"}
The alert is always undefined. Am I missing something?
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 : {
ponent_id : null
},
urlRoot : "/ponents/ajax_ponent",
});
ComponentsView = Backbone.View.extend({
el : $('body'),
events : {
'change #ponent-selector' : 'changeComponent',
},
initialize : function() {
_.bindAll(this, 'render', 'changeComponent');
this.render();
},
changeComponent : function(e) {
var clickedEl = $(e.currentTarget);
var value = clickedEl.attr("value");
var ponent = new ComponentsModel({id :value, ponent_id :value });
ponent.fetch();
ponent.toJSON();
alert(ponent.get('ponent_name'));
},
render : function() {
},
});
And the JSON being return from the server looks like this:
{"ponent_id":"1","ponent_name":"Test Component 1","ponent_description":"A simple test ponent","ponent_required":"","user_id":"1","ponent_approved":"0","ponent_price":"0","ponent_overview":"'"}
The alert is always undefined. Am I missing something?
Share Improve this question asked May 26, 2012 at 18:03 Devin DixonDevin Dixon 12.5k24 gold badges97 silver badges179 bronze badges1 Answer
Reset to default 7Fetch is async, that's why it has success
and error
callbacks. So it's no sure that the data are fetched by the time you try to get the property.
Try this:
ponent.fetch({
success: function(){
// Now you got your data
}});