I have an express app with session in the back end, and in the front I have Backbone+RequireJS. My problem is with the session Model I have, and the change event that triggers the render method on the views.
So:
So, the question is: How do I avoid this bad behavior, so the views only listen to events if the correct route is active?
A code example:
"use strict";
var SessionModel = Backbone.Model.extend({});
var sessionModel = new SessionModel();
var HomeView = Backbone.View.extend({
initialize: function() {
this.listenTo(sessionModel, "change", this.render);
},
render: function() {
// updates the main container element
}
});
var AppRouter = Backbone.Router.extend({
"": "home",
"about": "about"
});
var appRouter = new AppRouter();
appRouter.on("route", function() {
sessionModel.fetch(); // Updates session model on every route change
});
appRouter.on("route:home", function() {
var homeView = new HomeView();
homeView.render();
});
You can listen for an expecific attribute instead of listen for every kind of change.
this.bind("change:SomeExpecificThing", doEspecificThing)
I found a solution to my problem:
sessionModel.on("change", function () {
Backbone.history.loadUrl();
}).fetch();
With this we trigger the correct route and render again without adding listeners to the views.