Backbone router.on event not firing from url - javascript

I am trying to fire a backbone event when the user inputs the URL (whatever.com)/questions/new.
my router looks like the following:
define(['backbone'],function(BackBone){
var routeExtend = Backbone.Router.extend({
routes: {
"": "home",
"questions/new": 'newQuestion'
},
});
var initialize = function(){
var Router = new routeExtend();
Router.on('route:newQuestion', function() {
console.log('new question');
});
BackBone.history.start();
return Router;
}
return {initialize:initialize};
});
And if I call router.navigate within my app, the event fires fine.
However, I want to be able to fire the "on" event if "questions/new" is the initial URL given to the web browser. Is there any way to do this?

you could define the function instead of router.on event
var routeExtend = Backbone.Router.extend({
routes: {
"": "home",
"questions/new": 'newQuestion'
},
newQuestion: function() {
console.log('new question');
}
});

Related

Redirect or render another view on event

I'm building a little CRUD app in Backbone, and I'm stuck a little with a need to redirect from one view to another. My app consists of a layout view, in which other views are rendered, and a router. Here it is:
var router = Backbone.Router.extend({
routes: {
'': 'home',
'resumes/:id': 'showResume'
},
home: function () {
// renders a index view with my collection
this.layout.render(new ResumeList({collection: resumes});
},
showResume: function () {
if (!this.fullResume) {
this.fullResume = new FullResume({model: new Resume()});
}
// allowing to navigate via url with model id
this.fullResume.model.set('id', id).fetch({
context: this,
success: function () {
this.layout.render(this.fullResume);
}
});
}
});
Then, in my FullResume view I've got a delete event, which destroys the model. Here it goes:
var FullResume = Backbone.View.extend({
// tagName and other stuff
events: {
// other events
'click #delete': 'deleteResume'
},
// initialize, render and other functions
deleteResume: function () {
this.model.destroy({
success: function (res) {
console.log('DELETE model' + res.toJSON().id);
},
error: function () {
console.log('Failed to DELETE');
}
});
}
});
The function above works perfectly and deletes the model, but after deleting the model it still remains on it's view until I navigate somewhere manually. I read a bit and tried to manage how to render the main view after this event or redirecting to it, but didn't succeed a much.
You are looking for the http://backbonejs.org/#Router-navigate function with the trigger option set to true.
Here's an example: http://jsfiddle.net/x3t7u5p0/
Clicking on "Home" or "About" links will change the view, however I've added a delayed programmatic view change, when the About view renders, it will switch back to Home after the delay
render: function () {
this.$el.html(this.template);
_.delay(function() {
appRouter.navigate('home', {trigger: true});
}, 500);
}

Backbone routes are not working

I am creating a simple Backbone app and the routing is not working. Here is my router.
define(function(require) {
'use strict';
var Backbone = require('backbone');
var Header = require('views/header.view');
var MainBody = require('views/main.body.view');
var Router = Backbone.Router.extend({
routes: {
"": "main",
"about/": "about"
},
main: function() {
var header = new Header();
$('#header').html(header.render());
var body = new MainBody();
$('#app').html(body.render());
},
about: function() {
console.log("About");
}
});
return Router;
});
I hit the / route as expected, but when I go to /about, it never hits the about function. Am I supposed to have a hash in the url somewhere? What else could I be missing that would cause this issue?
It's because routes are explicitly matched, so "about/": "about" will match /about/ and "about": "about" will match /about
There is a way to match both /about and /about/ and it requires using optional matchers (matcher) so your routes hash key will look like this
"about(/)": "about"
For hashless routes to work you need to run Backbone.history.start({pushState: true}).
According to backbonejs documentation, routers should be defined and addressed as follows:
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});
Therefore, when you type http://<URL>/backbonepage#help, the help function will be invoked

Backbone router.navigate how to pass dynamic ID

Using backbone marionette I need to navigate to the following route:
'page/:id': 'page'
This is what I have tried so far:
success: function (page) {
id = page.get('id')
router.navigate('page', {trigger: true});
}
But I have two problems with above.
1) Router is undefined in my view
2) I cannot find a reference to how I pass the ID
How do I resolve this or does marionette have any build in methods?
You can pass the id just putting it in the url:
success: function (page) {
id = page.get('id')
router.navigate('page/' + id, {trigger: true});
}
Reference
Regarding the router you need to create it:
var MyRouter = Backbone.Router.extend({
routes: {
'page/:id': 'page'
},
page: function(id) {
...
}
});
var router = new MyRouter();

How does one "listen to the router" (respond to Router events in Views/Models) in Backbone.js?

In the Backbone.js documentation, in the entry for the Router.routes method, it is stated
When the visitor presses the back button, or enters a URL, and a particular route is matched,
the name of the action will be fired as an event, so that other objects can listen to the router,
and be notified.
I have attempted to implement this in this relatively simple example:
The relevant JS:
$(document).ready(function(){
// Thing model
window.Thing = Backbone.Model.extend({
defaults: {
text: 'THIS IS A THING'
}
});
// An individual Thing's View
window.ThingView = Backbone.View.extend({
el: '#thing',
initialize: function() {
this.on('route:showThing', this.anything);
},
anything: function() {
console.log("THIS DOESN'T WORK! WHY?");
},
render: function() {
$(this.el).html(_.template($('#thing-template').html(), {
text: this.model.get('text')
}));
return this;
}
});
// The Router for our App
window.ThingRouter = Backbone.Router.extend({
routes: {
"thing": "showThing"
},
showThing: function() {
console.log('THIS WORKS!');
}
});
// Modified from the code here (from Tim Branyen's boilerplate)
// http://stackoverflow.com/questions/9328513/backbone-js-and-pushstate
window.initializeRouter = function (router, root) {
Backbone.history.start({ pushState: true, root: root });
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href.slice(protocol.length) !== protocol) {
evt.preventDefault();
router.navigate(href, true);
}
});
return router;
}
var myThingView = new ThingView({ model: new Thing() });
myThingView.render();
var myRouter = window.initializeRouter(new ThingRouter(), '/my/path/');
});
The relevant HTML:
<div id="thing"></div>
<!-- Thing Template -->
<script type="text/template" id="thing-template">
<a class='task' href="thing"><%= text %></a>
</script>
However, the router event referenced in the View's initialize function does not seem to get picked up (everything else works--I'm successfully calling the "showThing" method defined in the Router).
I believe I must have some misconception about what the documentation intended by this statement. Therefore, what I'm looking for in a response is: I'd love to have someone revise my code so that it works via a Router event getting picked up by the View, or, clearly explain what the Router documentation I listed above intends us to do, ideally with an alternative code sample (or using mine, modified).
Many thanks in advance for any assistance you can provide!
This is beacuse you are binding a listener to the wrong object. Try this in your View :
window.ThingView = Backbone.View.extend({
initialize: function() {
myRouter.on('route:showThing', this.anything);
},
...

Backbone router issue

I have a router that does the site navigation nicely and also works when clicking the browsers back / forward button. However, when entering directly an URL I get 404.
Here is my router:
define(function(require) {
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');
var AppRouter = Backbone.Router.extend( {
routes: {
'home' : 'homeHandler',
'webdesign' : 'webHandler',
'mobile' : 'mobileHandler',
'javascript' : 'javascriptHandler',
'hosting' : 'hostingHandler',
'contact' : 'contactHandler'
},
initialize: function() {
this._bindRoutes();
$('.link').click(function(e){
e.preventDefault();
Backbone.history.navigate($(this).attr("href"),true);
});
if(history && history.pushState) {
Backbone.history.start({pushState : true});
console.log("has pushstate");
}
else {
Backbone.history.start();
console.log("no pushstate");
}
console.log("Router init with routes:",this.routes);
},
homeHandler: function(e) {
require(['../views/home-content-view', '../views/home-sidebar-view'],
function(HomeContent, HomeSidebar) {
var homeContent = new HomeContent();
homeContent.render();
var homeSidebar = new HomeSidebar();
homeSidebar.render();
});
},
webHandler: function(e) {
require(['../views/web-content-view', '../views/web-sidebar-view'],
function(WebContent, WebSidebar) {
var webContent = new WebContent();
webContent.render();
var webSidebar = new WebSidebar();
webSidebar.render();
});
},
...
});
return AppRouter;
});
Obviously, I'm missing something.
Any clarification would be greatly appreciated.
Thanks,
Stephan
Backbone operates on a web-page (that has already been loaded in the browser). When you enter a URL in the browser directly, you're making a HTTP-request for that URL to the server. The server is not managed by Backbone. You have to define on the server the behavior when such HTTP-requests are encountered.

Categories

Resources