-
-
Save juanghurtado/2949288 to your computer and use it in GitHub Desktop.
// Model | |
module.SampleModel = Backbone.Model.extend({}); | |
// View | |
module.SampleView = Backbone.Marionette.ItemView.extend({ | |
template : template_string, | |
// This trigger runs only the first time. After that, "click" event is not triggered (defaults to href="#") | |
triggers : { | |
'click .reload' : 'reload' | |
}, | |
initialize : function() { | |
this.bindTo(this.model, "change", this.modelChanged); | |
this.model.fetch(); | |
}, | |
modelChanged : function() { | |
// App has a Marionette.Region called "mainRegion" | |
App.mainRegion.show(this); | |
} | |
}); | |
// Init | |
var model = new module.SampleModel(); | |
var view = new module.SampleView({ | |
model : model | |
}); | |
view.on('reload', function() { | |
console.log('reload event'); | |
model.fetch(); | |
}); |
You can defer the rendering and displaying of the model until after the data has been loaded, like this:
var model = new module.SampleModel();
var view = new module.SampleView({
model : model
});
// the "sync" event triggers after the data has been loaded from the server
model.on('sync', function() {
App.mainRegion.show(view);
});
model.fetch();
Oops… I feel like an idiot. Of course that is the way!
Thank you again, Derick. You deserve a donation on Marionette, sir!
and thank you! i really appreciate that :)
Are you sure that the event on the model is "sync". It does not trigger when doing it this way:
var weatherModel = new module.WeatherModel({});
var weatherView = new module.WeatherView({
model : weatherModel
});
weatherModel.on('sync', function() {
App.mainRegion.show(weatherView);
});
weatherModel.fetch();
Data is fetched from the server (checked on browser console). If I use "all" on model event, the callback is executed many times, but not when using just "sync".
I'm looking on Backbone.js events catalogue, but none of them seems logic (except "sync"). Maybe "reset", but it is just for Collections
Is this a better approach?
weatherModel.fetch({
success : function() {
App.mainRegion.show(weatherView);
}
});
I thought 'sync' was supposed to work like that... but the success callback would work certainly
Thanks a lot for your time, Derick. It's awesome to have people like you on the community. Kudos to you!
I'm still lost about this. I need to show my view once the model is fetch from the server, that's why I had it on the "change" event of the model itself. If I to the
region.show(view)
outside of the "change" event it throws an error complaining about undefined vars that I'm using inside the template of the view (obviously, that vars don't exists yet because the model is being fetched).How this simple requeriment should be approached?