Backbone: Navigate does not hit the specified route - javascript

Calling navigate after saving a model.
this.model.save({},{
success: function(model, response, options){
Backbone.history.navigate('getCampaigns', {tigger: true});
}
});
But it never hits the specified route.
Route class
var Router = Backbone.Router.extend({
routes: {
"":"home",
"login":"login",
"getCampaigns":"getCampaigns"
},
start: function() {
Backbone.history.start({pushState:true});
},
home: function() {
var loginView = new LoginView({model: loginModel});
loginView.render();
$(".container").append(loginView.el);
},
login: function(event) {
event.preventDefault();
},
getCampaigns: function() {
this.dashboardList.fetch();
$('.container').html(this.dashboardListView.render().el);
}
});
var app = new Router();
app.start();

You have an error in your code :
Backbone.history.navigate('getCampaigns', {trigger: true}); // not {tigger: true}

Related

Backbone: Best way to prevent routes (and url change)

I have an editor view and if there are unsaved changed I am prompting on window closes and also on backbone routes.
Problem is that Backbone.Router.execute runs after the url change and so I am trying to implement the most reliable and elegant way of preventing the url change.
In the example below clicking the "About" route will prevent the route callback and then rewind the url change - it seems less than ideal that I have to use window.history.back() (because it creates a history entry).
Can you think of a better way? I know a jQuery on-click can catch the event before url change but I'm not sure how to nicely integrate that with a Backbone.Router. Thanks.
var HomeView = Backbone.View.extend({
template: '<h1>Home</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AboutView = Backbone.View.extend({
template: '<h1>About</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var ContactView = Backbone.View.extend({
template: '<h1>Contact</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
'about': 'aboutRoute',
'contact': 'contactRoute'
},
execute: function(callback, args, name) {
if (window.location.hash === '#/about') {
window.history.back();
return false;
}
if (callback) {
callback.apply(this, args);
}
},
homeRoute: function () {
var homeView = new HomeView();
$("#content").html(homeView.el);
},
aboutRoute: function () {
var aboutView = new AboutView();
$("#content").html(aboutView.el);
},
contactRoute: function () {
var contactView = new ContactView();
$("#content").html(contactView.el);
}
});
var appRouter = new AppRouter();
Backbone.history.start();
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div id="navigation">
Home
About
Contact
</div>
<div id="content"></div>
The only thing I can think of is listening to clicks and doing things with jQuery, or saving the last hash and doing window.history.replaceState(undefined, undefined, "#last_hash_value").

Backbone fetch producing 404 error

I have the following backbone model node that I am trying to use to fetch data from the server but at the moment I get a 404 error, I have checked my files and they seem to be correct
var app = app || {};
app.NotesModel = Backbone.Model.extend({
url:'/usernotes',
defaults: {
username:'',
email:'',
about:'',
editorNote:''
}
});
app.NotesView = Backbone.View.extend({
el:'#notes',
events: {
'click #save': 'save'
},
template1: _.template($('#about').html()),
template2: _.template($('#facts').html()),
initialize: function() {
app.NotesModel = new app.NotesModel({});
var email = $('#data-user').text();
app.NotesModel.fetch({data: {email: email},type:'GET' });
this.render();
},
render: function() {
},
This is what the route file looks like
app.get('/account/usernotes/', require('./views/account/usernotes/index').init);
app.get('/account/usernotes/:email', require('./views/account/usernotes/index').find);
and the functions for the routes
'use strict';
exports.init = function(req, res){
if (req.isAuthenticated()) {
//console.log(req.user.email);
res.render('account/usernotes',
{ data : {
user : req.user.email
}
});
}
else {
res.render('signup/index', {
oauthMessage: '',
oauthTwitter: !!req.app.config.oauth.twitter.key,
oauthFacebook: !!req.app.config.oauth.facebook.key,
oauthGoogle: !!req.app.config.oauth.google.key
});
}
};
exports.find = function(req,res) {
console.log('here');
console.log(JSON.stringify(req));
}
Doing the console.log() doesn't give me any output at all.
Here is a similar question.
Try this:
app.NotesModel.fetch({data: $.param({email: email}) });
or this:
app.NotesModel.fetch({data: {email: email}, processData: true });

Backbone.js route methods not getting called

I've searched various other similar StackOverflow questions but none of them seemed to offer a solution. I have the following backbone router setup:
var AppRouter = Backbone.Router.extend({
routes: {
"" : "homeAction",
"/portfolio" : "portfolioAction",
"/about_us" : "aboutUsAction",
"/contact" : "contactAction"
},
initialize: function () {
},
homeAction: function () {
alert("User has navigated home");
},
portfolioAction : function() {
alert('user have navigated to portfolio');
},
servicesAction: function () {
alert("User has navigated to services");
},
aboutUsAction: function () {
alert("User has navigated to about us");
},
contactAction: function () {
alert("User has navigated home");
},
requestQuoteAction: function () {
alert("User has requested to submit a quote");
}
});
var app = new AppRouter();
$(function() {
Backbone.history.start();
});
When I navigated to mydomain.com/# The homeAction route gets called as expected. However if I try navigating to mydomain.com/#/portfolio, nothing happens. Any idea why this method is not getting called?
Removing the slash at the begining of your route should work.
var AppRouter = Backbone.Router.extend({
routes: {
"" : "homeAction",
"portfolio" : "portfolioAction",
"about_us" : "aboutUsAction",
"contact" : "contactAction"
},
...
Then try to go to mydomain.com/#portfolio for example.

Backbone unwanted route redirect on webkit

I have an unwanted route redirect after authentification
My base url is
http://127.0.0.1:8020/VT/
If the user isn't logged in localstorage, i'll load the login view.
The main menu view render correctly if the login succeed,
I have this unwanted automaticaly redirection to
http://127.0.0.1:8020/
This only happen on webkit browser. (haven't tried on IE)
Router = new MainRouter();
Backbone.history.start({
pushState: false,
root: "/VT/"
});
var MainRouter = Backbone.Router.extend({
routes: {
"": "login",
"login": "login",
"main": "mainMenu"
},
showView: function(view){
if (this.currentView){
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$('#wrapper').html( this.currentView.el );
},
login: function(){
var result = app.session.isLoggedIn();
if(result == true){
this.navigate('main', {trigger: true, replace: true});
}
else{
var loginView = new LoginView();
this.showView( loginView );
}
},
mainMenu: function(){
var mainMenu = new MainMenuView();
this.showView( mainMenu );
},
});
var LoginView = Backbone.View.extend({
name: "Login",
el: $('#page-login'),
initialize : function() {
this.template = _.template( app.get("tpl/nav/login.html") );
this.clearStatusBar();
},
render: function(){
var renderedContent = this.template();
$(this.el).html(renderedContent);
return this;
},
events: {
"click input[type=submit]": "loginAction"
},
validate: function(){
// some validation code
},
loginAction: function(){
if( this.validate() ){
app.router.navigate('main', {trigger: true, replace: true});
}
else{
alert('Login failed');
}
},
});
I can't figure it out why. Any suggestions ?

How to handle a simple click event in Backbone.js?

I am having difficulty with something very simple in Backbone. I want to wire up the <h1> in my page so that when the user clicks on it, it returns seamlessly to the homepage, without a postback.
This is the HTML:
<h1><a id="home" href="/">Home</a></h1>
(UPDATE: fixed ID as suggested by commenter.) And this is my Backbone view and router:
var HomeView = Backbone.View.extend({
initialize: function() {
console.log('initializing HomeView');
},
events: {
"click a#home": "goHome"
},
goHome: function(e) {
console.log('goHome');
e.preventDefault();
SearchApp.navigate("/");
}
});
var SearchApp = new (Backbone.Router.extend({
routes: {
"": "index",
},
initialize: function(){
console.log('initialize app');
this.HomeView = new HomeView();
},
index: function(){
// do stuff here
},
start: function(){
Backbone.history.start({pushState: true});
}
}));
$(document).ready(function() {
SearchApp.start();
});
The console is showing me
initialize app
initializing HomeView
But when I click on the <h1>, the page posts back - and I don't see goHome in the console.
What am I doing wrong? Clearly I can wire up the <h1> click event simply enough in jQuery, but I want to understand how I should be doing it in Backbone.
If you enable pushState you need to intercept all clicks and prevent the refresh:
$('a').click(function (e) {
e.preventDefault();
app.router.navigate(e.target.pathname, true);
});
Something like:
$(document).ready(function(){
var HomeView = Backbone.View.extend({
initialize: function() {
console.log('initializing HomeView');
}
});
var AboutView = Backbone.View.extend({
initialize: function() {
console.log('initializing AboutView');
}
});
var AppRouter = Backbone.Router.extend({
routes: {
"": "index",
"about":"aboutView"
},
events: function () {
$('a').click(function (e) {
e.preventDefault();
SearchApp.navigate(e.target.pathname, true);
});
},
initialize: function(){
console.log('initialize app');
this.events();
this.HomeView = new HomeView();
},
index: function(){
this.HomeView = new HomeView();
},
aboutView : function() {
this.AboutView = new AboutView();
}
});
var SearchApp = new AppRouter();
Backbone.history.start({pushState: true});
});
Your tag id is invalid, try this:
<h1><a id="home" href="/">Home</a></h1>

Categories