router function not triggering - backbone.js

In my backbone function, i am navigating a id to routers, but the function not calling... as well i have given the different sample navigate urls to my links, those are not calling the functions..
mycode :
(function($){
var myRouter = Backbone.Router.extend({
routes:{
"":"defaultRoute", //onload it works
'#/name/:id':"nameData",
// i am calling this function on default Router
'#/project/:id':"projectData"
},
defaultRoute:function(){
console.log('default')
startRoute.navigate("#/name/3"); // i am redirecting
},
nameData:function(id){
console.log(id); // id not consoling not called this func.
},
projectData:function(project){
console.log(project);
}
});
var startRoute = new myRouter();
Backbone.history.start();
})(jQuery);
my url : http://localhost:85/router/web/#/name/3
my html :
<ul class="name">
<li>name1</li>
<li>name2</li>
<li>name3</li>
<li>name4</li>
<li>name5</li>
</ul>
any one find me the wrong this what i do here.. please

All my functions are correct, by mistrake i added the hash on the routes prams.
update function here:
(function($){
var myRouter = Backbone.Router.extend({
routes:{
"":"defaultRoute",
'name/:id':"nameData",
'product/:id':"projectData"
},
defaultRoute:function(){
console.log('i am default');
},
nameData:function(e,id){
console.log(id);
},
projectData:function(project){
console.log(project);
}
});
var startRoute = new myRouter();
Backbone.history.start();
})(jQuery);

Related

Marionette js routing - What am I doing wrong here? I'm getting error that route actions are undefined?

Just want to get some basic routing up and going. Having seen a number of examples I thought the code below should work, but when I run I get the error "Unable to get property 'doChat' of undefined or null reference". Do I have the initialization sequence wrong?
require(["marionette", "jquery.bootstrap", "jqueryui"], function (Marionette) {
window.App = new Marionette.Application();
App.start();
App.addRegions({
//add some regions here
});
//Set up routing
var AppRouter = Marionette.AppRouter.extend({
appRoutes: {
"": "doDefault",
"chat": "doChat"
},
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
});
var router = new AppRouter();
//History
if (Backbone.history) {
Backbone.history.start();
}
})
The AppRouter allows two types of routes, standard backbone routes as defined in the routes property and routes which call functions in another object defined in the appRoutes property.
So to get you above code working, you can do one of two things. The quickest is simply to change the appRoutes property to routes which will do normal backbone routing. The second option is to create another object and pass that to the AppRouter as the controller during instantiation:
var myController = {
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
}
var router = new AppRouter({
controller: myController
});
This is detailed in the AppRouter documentation.

Getting actions to fire with backbone

Iv'e set up my first little backbone app with a router to see if i can get some actions firing. I can't. I don't get an error message, but the console.log messages aren't displaying. Is there something more I have to set up to get the app started?
window.BreakfastApp = new (Backbone.Router.extend({
routes: { "": "interest", "products/:type": "products"},
initialize: function(){
console.log("hello world");
},
start: function(){
Backbone.history.start({pushState: true});
},
interest: function(){
console.log('interest')
},
products: function(type){
console.log('product' + type )
},
toppings: function(){
console.log('toppings')
},
results: function(){
console.log('results')
}
}));
$(function(){
BreakfastApp.start();
});
The documentation says:
During page load, after your application has finished creating all of
its routers, be sure to call Backbone.history.start(), or
Backbone.history.start({pushState: true}) to route the initial URL.
In your case something like:
var BreakfastAppRouter = Backbone.Router.extend({
...
});
var router = new BreakfastAppRouter();
Backbone.history.start();
should do the job.

Backbone pushstate history not working

I am using backbone.js routes and i am struggling to make history to work. Here is the code i have:
$(function() {
var AppRouter = Backbone.Router.extend({
routes: {
"/": "initHome",
"home": "initHome",
"projects": "initProjects",
"project/:id" : "initProject"
}
});
// Instantiate the router
var app_router = new AppRouter;
app_router.on('route:initProject', function (id) {
// Note the variable in the route definition being passed in here
getContent("project",id);
});
app_router.on('route:initProjects', function () {
getContent("projects");
});
app_router.on('route:initHome', function () {
getContent("home");
});
// SINGLE PAGE MAGIC
$(document).on("click",".links",function(e) {
var href = $(this).attr("href");
var url = lang + "/" + href;
page = $(this).attr("data-id");
var param = $(this).attr("data-param");
if (typeof(param) == 'undefined') { param = ""; }
if(activepage != href && !main.hasClass("loadingPage")){
loader.show();
firstInit = false;
activepage = href;
res = app_router.navigate(url, true);
getContent(page,param);
}
return false;
});
Backbone.history.start({pushState: true, root: "/karlin/"});
});
Push state is working fine on click, but it wont call getContent() function when i try back/next buttons in the browser. I am an newbie to backbone, so any advice will be helpful.
Change this: res = app_router.navigate(url, true);
To this: app_router.navigate(url, {trigger: true});
I can't see any reason to create a variable "res".
IMHO you've got a convoluted implementation of Backbone. I'd suggest moving your routes to the constructor like so:
var AppRouter = Backbone.Router.extend({
routes: {
"/": "initHome",
"home": "initHome",
"projects": "initProjects",
"project/:id" : "initProject"
},
initProject: function (id) {
// Note the variable in the route definition being passed in here
getContent("project", id);
},
initProjects: function () {
getContent("projects");
},
initHome: function () {
getContent("home");
}
});
// Instantiate the router
var app_router = new AppRouter;
Also, if you set up your routes properly like in the Backbone docs,
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
you can pass parameters to the routes with traditional links. You can also move your if activePage statement to the router as a helper function for changing pages.
Router.navigate is for rare instances.
I suggest, reading the Backbone docs over and over. I learn something new every time. There's a lot there and Backbone is doing things efficiently already. No need to reinvent the wheel.
Hope this helps!
I second Andrew's answer: your use of routing is a bit odd.
If you're interested in learning more about why, as Andrew says, "Router.navigate is for rare instances", read pages 32-46 here: http://samples.leanpub.com/marionette-gentle-introduction-sample.pdf
It's part of the sample for my book on Backbone.Marionette.js, but routing concepts remain the same. In particular, you'll learn why the default trigger value is false, and why designing your app routing with that in mind will make your apps better.

Backbone.Marionette controller not working

I have a Backbone.Marionette app configured using the AppRouter as well as the EventAggregator.
The initializer starts the router, and then history. I know for sure that my EventAggregator is set up properly - MyVent.trigger('abc') works properly in the console. The AppRouter also seems to be working properly as navigating to an undefined URL results in a 404, as expected.
Am I missing something?
//Initializer
MyApp.addInitializer(function(options){
//do stuff here
router = new MyRouter(MyController);
console.log('routing started!');
MyVent.trigger('routing:started'); <-- this works
});
//EventAggregator
MyVent = new Backbone.Marionette.EventAggregator();
MyVent.on('contactUs', function(){
console.log('ContactUs received by MyVent!');
startContactUsModal();
Backbone.history.navigate("contactus/");
});
MyVent.on('bookNow', function(){
console.log('BookNow received by MyVent!');
startBookNowModal();
Backbone.history.navigate("booknow/");
});
MyVent.on('home', function(){
console.log('home received by MyVent!');
startHome();
console.log('after starthome on myvent');
});
MyVent.on('routing:started', function(){
console.log('routing:started recieved at MyVent!');
if( ! Backbone.History.started) Backbone.history.start();
console.log('Backbone.history sucessfully started!');
});
//Controller
MyController = {
homeMethods:function(){
console.log('home receieved at mycontroller');
MyVent.trigger('home')
},
booknowMethods:function(){
MyVent.trigger('bookNow')
},
contactusMethods:function(){
MyVent.trigger('contactUs')
}
};
//Router
MyRouter = Backbone.Marionette.AppRouter.extend({
controller: MyController,
routes: {
'' : 'homeMethods',
'tours' : 'toursMethods',
'booknow' : 'booknowMethods',
'contactus' : 'contactusMethods'
},
});
WOW! What a stupid mistake - at least I'm getting faster at identifying these.
Declaring routes in AppRouter, is different than in the Backbone router.
Marionette: appRoutes
Regular Backbone: routes

Backbone - Update URL from view function

I'm stumbling through my first backbone project, and am trying to update the URL after a button element is clicked.
I can manually set the URL via window.location.hash, but I assume this is not the correct way. Can anyone tell me what is the preferred way to update the URL?
var AppView = Backbone.View.extend({
events: {
"click #loadProject": "filterProject",
},
filterProject: function(){
var projectID = $('#selectProject option:selected').val();
var orgID = 'test';
// Is there a better way to do this?
window.location.hash = '/'+orgID+'/'+projectID;
this.renderProject(orgID,projectID);
},
renderProject:function(orgID,projectID){
//Some code
},
});
//Routing
var PropertiesRouter = Backbone.Router.extend({
routes: {
"/:who/:project":"getProjects", //#/org/1
"/:who":"getOrganisation", //#/org
"*actions": "defaultRoute"
},
getProjects:function(who,project){
app.renderProject(who,project);
},
getOrganisation:function(who){
app.renderOrganisation(who);
},
defaultRoute: function(actions){
app.renderHomePage();
},
});
var app = new AppView();
//create router instance
var propertiesRouter = new PropertiesRouter();
//start history service
Backbone.history.start();
Thanks!
You definitely can call window.location.hash, but this does break some of the separation backbone is trying to create for you. A better choice is to call router.navigate(..). See http://backbonejs.org/#Router-navigate

Resources