I must be losing it. I've set up the simplest Backbone app, but can't seem to get routes to respond. Here's my router (in coffeescript):
class BackboneSupport.Routers.TicketsRouter extends Backbone.Router
initialize: ->
#tickets = new BackboneSupport.Collections.TicketsCollection()
routes:
"/new" : "newTicket"
".*" : "index"
newTicket: ->
alert 'hi, from the new ticket route'
index: ->
// just to prove a point
$('#tickets').html('tickets go here')
#navigate('/new')
And I get the whole train moving with:
<div id="tickets"></div>
<script type="text/javascript">
$(function() {
window.router = new BackboneSupport.Routers.TicketsRouter();
Backbone.history.start();
});
</script>
As you would expect, the root route (index) populates #tickets with placeholder text and successfully navigates to the /new route (confirmed via the address bar), however, it does not alert anything, meaning the newTicket method is not being triggered.
What am I missing here?
UPDATE:
Per rjz below, I updated the navigate method to:
#navigate('/new', {trigger: true})
But strangely, still no alert :/
You shouldn't have the leading slash in your route, you want this:
class BackboneSupport.Routers.TicketsRouter extends Backbone.Router
routes:
"new": "newTicket"
".*" : "index"
#...
Demo: http://jsfiddle.net/ambiguous/veSDF/1/
From the fine manual:
extend Backbone.Router.extend(properties, [classProperties])
[...] Note that you'll want to avoid using a leading slash in your route definitions:
Related
Here is my A tag in index.html.
<div class="menu-item">Login in
If I click it, it should go to '/login' route. But URL correctly changed to localhost:3333/#login in browser address input bar, but the page content shows no change, still in landing page.
Here is my code for starting Backbone history:
new Router();
Backbone.history.start({pushState: true, root: '/'});
Here is my code for router:
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;
var _ = require('lodash');
var Marionette = require('backbone.marionette');
var OuterLayout = require('../layout/outerLayout/outerLayout');
var ol = new OuterLayout();
var AppRouter = Backbone.Marionette.AppRouter.extend({
routes : {
'': 'index',
'signup' : 'signup',
'login' : 'login'
},
index : function () {
if(_.isEmpty(ol.el.innerHTML)) {
ol.render();
}
// outerLayout.footer.show();
},
signup : function () {
if(_.isEmpty(ol.el.innerHTML)) {
ol.render();
}
var ContentSignup = require('../layout/outerLayout/view/contentSignup/contentSignup');
ol.content.show(new ContentSignup());
},
login: function () {
if(_.isEmpty(ol.el.innerHTML)) {
ol.render();
}
var ContentLogin = require('../layout/outerLayout/view/contentLogin/contentLogin');
ol.content.show(new ContentLogin());
}
});
module.exports = AppRouter;
The result is that URL changed in the browser address input field, but the page content doesn't change. Then if I hit CMD + R to refresh the page, then the content will change, correctly reflecting the route.
Also the go back button on browser doesn't work, url changes, but the content doesn't change. I think I forget to call sth in my code to "refresh" the browser?
oh, I am using httpster to start a mini http server for this front-end development.
Have you tried this:
new AppRouter();
instead of this
new Router();
Unless you actually want to hit the server (which would just be /login and you'd deal with it on the server side). You should take the pub sub approach.
So in your view you would say:
triggers
"click .menu-item": "loginClicked"
Then in your controller you can listen to that event (if it's a composite view's childview that you're in you may have to prefix this with childview:):
#listenTo loginView, "login:button:clicked", (args) ->
App.vent.trigger "login:clicked"
Then in the router
API =
login: ->
new LoginsApp.Show.Controller
App.vent.on "login:clicked", ->
App.navigate "/login"
API.login()
So you end up navigating/hitting the same action that you would by going through the router, but you don't have to rely on the routes.
If you don't want to go that route I imagine the problem is that you need to say Backbone.history.navigate({trigger: true}) to get it to actually trigger the route in the approuter.
The best approach I've found is the approuter is there when the user clicks refresh or navigates directly to the page. But everything else should be handled in app with the pub sub approach. It gives you the most control that way.
Remove the slash (/) and use only "#route" on your hrefs, to avoid the browser from fetching the default document served at "/" from the backend.
By the way, watch your use of require, you should require the constructors at the top so the requirejs optimizer can fill in the dependencies on build time.
Something like:
//this before the component definition
var MyView = require("views/myview"),
AppLayout = require("views/layout");
//... later on your view/app/model definition
function foo(){
var view = new MyView();
}
I also think having a list of required stuff at the top of any file helps understanding it later on. ;)
I'd appreciate any insight into whether this is a "correct" way of doing things and also what's causing the error I'm seeing.
I have added backbone to my base meteor install meteor add backbone
Then I set up a router.js file as follows (just showing 2 pages as example);
var Router = Backbone.Router.extend({
routes: {
"": "index",
"help": "help",
...
},
index: function() {
Session.set('currentPage', 'homePage');
},
login: function() {
Session.set('currentPage', 'loginPage');
},
...
Then for the pages I have html files with templates looking something like this...
<template name="homepage">
{{#if route}}
You're at the Home Page!
{{/if}}
</template>
Then for the main page I have an html file that contains the following;
<body>
...
{{> homepage}}
{{> loginpage}}
{{> helppage}}
...
</body>
This works for all of the pages except the one designated 'homepage', this template is always rendered regardless of where I am on the site. e.g. myapp/ as the root page just displays the homepage template, but myapp/loginpage displays the loginpage template and the homepage template. So every single page displays the contest of the homepage template.
Any insight? (or better ways to structure).
Thank you
Finally a question that I can answer because it's what I've been doing 60 hours a week at work for the last few months :-P
You're doing a few things wrong here, and they're extremely simple fixes that will get you fired up in no time.
First thing
You need to instantiate all of your routers and then initialize Backbone.pushState().
// This is just how I have been doing it, there are many correct ways.
var LoadedRouters = {
Module1 : new Module1Router(),
Module2 : new Module2Router(),
...
};
// After all routes instantiated, we tell Backbone to start listening.
Backbone.history.start({ pushState : true, root : "/" });
It's very important that you set the root property correctly, or else weird things start happening.
Second thing
You HAVE TO list your routers from the most-specific to the least-specific, top-down. The URL structure you outlined above will ALWAYS match the first route and trigger it.
routes : {
"help/phones/newservice" : HandleNewServiceHelp(),
"help/phones/oldservice" : HandleOldServiceHelp(),
"help/phones(/:any)" : HandleAllPhoneHelp(),
"help(/:any)" : HandleAllHelp(),
"" : HandleAllUnmatchedRoutes()
};
Backbone.router can be a tricky thing to learn.
I'm working with trigger and backbone, and am trying to programmatically navigate to a url. This is all happening using the file:// protocol, as everything in running inside trigger io only.
This manual navigate though doesn't trigger the function associated with the route.
My router looks like this
var BARouter = Backbone.Router.extend({
routes: {
"users/sign_in": "userSignin",
"users/sign_up": "userSignup",
"": "catchAll"
},
userSignin: function(){
},
userSignup: function(){
forge.logging.info("in user signup----");
},
catchAll: function(){
}
});
var app_router = new BARouter();
BA.router = app_router;
Backbone.history.start({pushState: true});
and I'm manually navigating
BA.router.navigate(navigate_to("users/sign_up"), {trigger:true});
The navigate_to method just returns the full url in the form "file://users/sign_up".
But nothing is logged to the console, and the execution flows normally. Am I missing something here ?
Using pushState with file urls probably doesn't make sense, I'm also not sure why you need the navigate_to function.
Try setting pushState to false and navigate using the string of the route, i.e.:
BA.router.navigate("users/sign_up", {trigger:true});
I have the following routes object:
routes: {
"*defaults": "home",
'#test': 'test'
}
Here's the url options:
myApp.html // home is called as desired
myApp.html#test // home is called instead of test
What did I miss?
Per the docs, you don't need the hash mark in the route (that's implied by the Backbone routing convention). Also, the "*defaults" route is going to catch everything, so you should put it last after more specific routes. So, like this:
routes: {
'test': 'test'
"*defaults": "home",
}
Should result in myApp.html#test getting routed to test.
I have a Backbone Router:
class X.Routers.Main extends Backbone.Router
routes:
'/': 'home'
'pageb': 'actionb'
'pagec': 'actionc'
Pages B and C work, but navigating to http://domain.ext/ results in a page reload instead of triggering the right route.
How can I prevent this?
You can either set "*path": "home" as your last route which will make it a default route or set "" (instead of "/")as your first route (which means root directory)
your base url path IS NOT "/", BUT "" (empty string)
I usually add optional "/" at the end of each route configuration, just in case
I also usually add default action handler at the end of configuration
So my routes configuration would be like:
routes = {
'': 'home',
'pageb(/)': 'actionB', // so /pageb or /pageb/ will call the same function
'pagec(/)': 'actionC', // so /pagec or /pagec/ will call the same function
'*action': 'defaultAction' // you can use it to render 404, or call home function
}
Hope this help