Backbone.js model attribute being returned undefined but debugging shows it set in console
I've been messing with backbone for a couple days now and coming up I guess with a misunderstanding in the order that backbone finally sets an attribute within a model. I have the following code:
Inside a model.js file -
SampleModel: Backbone.Model.extend({
urlRoot: 'a url',
defaults: {
attrA: 'value',
},
initialize: function() {
// init of model relationships
},
parse: function(response) {
this.set({attrA: response.attrAUpdateValue});
},
});
Inside a view.js file -
SampleView = Backbone.View.extend({
initialize: function() {
model = new SampleModel();
model.fetch();
console.log(model.get('attrA')); // Returns 'value' from default.
console.log(model.attributes); // Inspect the attributes for the model and see that attrA does not have updated value.
},
});
How do I ensure that 'attrA' has a value when working in the view outside of binding the model on change in order to work with attrA? Or, is that the way to think of it开发者_高级运维 in the realm of backbone? Do something with a model once an attribute has changed?
Thanks in advance for help.
UPDATE: My bad I've updated the comments accordingly, prior I had said that the first console log would contain an undefined value. It should have stated that the value is that of the default value and not the expected updated value that should have been set during the parse action.
The point is, Backbone fetch
is async. To ensure attrA
has value use success
callback:
SampleView = Backbone.View.extend({
initialize: function() {
model = new SampleModel();
model.fetch({success: function(){
console.log(model.get('attrA')); // Returns new value
});
},
});
精彩评论