I'm new in BackboneJS, RequireJS, JQuery apps development. I want to change the current view using router.navigate()
. This is the router configuration:
define([
//Libraries to load
"jquery",
"underscore",
"backbone",
"mustache",
//Views to load
"../views/Main",
"../views/Login",
"../views/Dashboard",
"../views/Empty"
], function ($, _, Backbone, Mustache, MainView, LoginView, DashboardView, HomeView) {
//All of the dependencies in the array above become parameters of the function to be managed
'use strict';
var AppRouter = Backbone.Router.extend({
routes: {
// Default
'*actions': 'defaultAction'
},
loadView: function(view){
this.view && (this.view.close ? this.view.close() : this.view.remove());
this.view = view;
this.view.render();
}
});
var initialize = function(){
var app_router = new AppRouter;
app_router.on('route:defaultAction', function (actions) {
switch (actions){
case "login": this.loadView(new LoginView()); break;
case "home": this.loadView(new HomeView()); break;
}
});
// Extend the View class to include a navigation method goTo (source: http://stackoverflow.com/questions/7755344/using-the-backbone-js-router-to-navigate-through-views-modularized-with-require)
Backbone.View.prototype.goTo = function (loc) {
app_router.navigate(loc, true);
};
Backbone.Model.prototype.goTo = function (loc) {
app_router.navigate(loc, true);
};
Backbone.history.start();
};
return {
initialize: initialize
};
});
In the Backbonejs View I use the following code to change/load views:
self.goTo("home");
But only change the hashtag in the URL. For example: #login
change to #home
, but not load the view. I have to reload page with the URL #home
to load the home view.
NOTE: Backbone.history.navigate("viewname", { trigger: true });
produce the same result. Change the URL but not route to view.
My router code with applied:
routes: {
'login': 'renderLogin',
'home': 'renderHome',
// Default
'*actions': 'renderDefault'
},
renderDefault: function(){
this.view = new MainView();
this.view.render();
},
renderLogin: function(){
this.view = new LoginView();
this.view.render();
},
renderHome: function(){
this.view = new HomeView();
this.view.render();
}
}