Reputation: 3977
In Backbone.js, how can i retrieve a veriable that is returned by a model function after the fetch has completed? As I understand the model cannot communicate with the view, so how can the view listen in on the model specific function fetch?
Thanks!
My attempt to do this can be seen below (if you see code mistakes, don't mind them, I wrote this as an example of what I'm trying to do):
var ScheduleModel = Backbone.Model.extend({
urlRoot: '/api/schedule/1',
getSubjectData: function(){
this.fetch({
success: function(data, scheduleData){
return scheduleData;
}
});
}
});
var ScheduleView = Backbone.View.extend({
initialize: function(){
console.log(this.model.getSubjectData());
}
});
Upvotes: 0
Views: 452
Reputation: 5308
You can do fetch
inside view like this.
var ScheduleView = Backbone.View.extend({
initialize: function(){
this.model.fetch({success: function() {
//you can do your stuff here.
//Try to get model data using `model.get`.
}});
}
}
and,
As I understand the model cannot communicate with the view.
This is wrong. You can set like this inside your view
.
this.model.view = this;
and you can access view in your model as like this.
this.view
But in my apps i am not doing this. Accessing view inside model will collapse the purpose of backbone.
Upvotes: 1
Reputation: 7133
You can listen to several model events with listenTo
:
http://backbonejs.org/#Events-listenTo
since model.fetch
triggers the 'change' event (http://backbonejs.org/#Model-fetch) somewhat similar in your view code:
var ScheduleView = Backbone.View.extend({
initialize: function(){
console.log(this.model.getSubjectData());
this.listenTo(this.model, 'change', this.doSmthng);
},
doSmthng: function () {
// ....
}
});
should fire the doSmthng
models' fetch is done.
Upvotes: 3