Backbone Router & Deep Linking - backbone.js

My single page web application consists of 4-5 views stacked vertically, when a user chooses a menu item, the page will scroll to the appropriate view. When you come into the application for the first time this is not a problem, however if you deep link to a menu item my page throws a fit because it's trying to access properties of an element that does not yet exists.
The problem I am having is understanding why the elements do not exist at the time the router is trying to scroll the page.
If you load / and then select home no problems, but if you directly hit #home via browser that when I get jQuery undefined errors.
Uncaught TypeError: Cannot read property 'top' of undefined
Inside router I am instantiating and rendering all of my views within the initialize function. The idea is the initialize will always happen before any of my routes, clearly not the case.
Again I've read a few threads that show how to have a before and after function for either all routes of individual routes but even using that approach scrollToById fails because it doesn't know what $(id) is at the time of being called.
define(function (require, exports, module) {
var Backbone = require('backbone');
return Backbone.Router.extend({
initialize: function(){
require(['ui/menu/menu','ui/home/home', 'ui/samples/samples', 'ui/resume/resume', 'ui/contact/contact'],
function(Menu, Home, Samples, Resume, Contact){
var menu = new Menu();
menu.render();
var home = new Home();
home.render();
var samples = new Samples();
samples.render();
var resume = new Resume();
resume.render();
var contact = new Contact();
contact.render();
});
},
routes: {
'' : 'init',
'home' : 'home',
'samples' : 'samples',
'resume' : 'resume',
'contact' : 'contact'
},
init: function(){
},
home: function (){
this.scrollToById($(".home-container"));
},
samples: function(){
this.scrollToById($(".samples-container"));
},
resume: function(){
this.scrollToById($(".resume-container"));
},
contact: function(){
this.scrollToById($(".contact-container"));
},
scrollToById: function(id) {
var val = $(id).offset().top - 127;
$('html, body').animate({
scrollTop: val
}, 2000);
}
});
});
Appreciate any tips or advice.

I think the routes event handlers in the router are getting initialized at the same time as the initialize function. Because of this, route events are getting triggered before the DOM elements are rendered.
I would try making a new function outside of Router that contains everything currently inside the initialize function. Then the final thing in that function can be to create an instance of the router. This will ensure that no routes events are called until your scripts and DOM are loaded.

Related

Backbonejs - Back button doesn't work if page transition on same page

Short description of my program and finally the problem:
I have got two pages. The first page list products in rows with a short description. If you click on one you will land on a detail page.
The detail page lists the product details and underneath a couple of related products. If you click on one of the releated products the same page is rendered again with the new information fetched from a REST interface.
If I want to use the browser-back-button or the own back-button to get to the previous product-detail-page a blank page appears. This only happens on my iPad. Using Chrome on a desktop browser works fine. I debugged the application and I figured out, that the backbonejs route is never called. I have no idea why.
Here is my code of the details page:
define([
"jquery",
"lib/backbone",
"lib/text!/de/productDetails.html"
],
function(
$,
Backbone,
ContentTemplate
){
var PageView = Backbone.View.extend({
// product details template
template: _.template(ContentTemplate),
// back-button clicked
events:{
'click a#ac-back-button':'backInHistory',
},
// init
initialize: function(options){
this.options=options;
// bind functions
_.bindAll(this,
'render',
'renderRelatedSeriePlainproduct',
'backInHistory'
);
// listen for collection
this.listenTo(this.options.relatedCollectionPlainproduct, 'reset',this.renderRelatedSeriePlainproduct);
},
// back button
backInHistory: function(e){
e.preventDefault();
window.history.back();
},
// render template
render: function(){
// render template
this.$el.html(this.template(this.model.models[0].attributes));
return this;
},
// render related products
renderRelatedSeriePlainproduct: function (){
var models = this.options.relatedCollectionPlainproduct.models;
if(models.length==0){
$('.ac-plainproduct').hide();
} else{
var elem = $('#ac-related-listing-plainproduct');
var ct="";
ct+='<ul id="ac-list-related-plainproduct">';
$.each(models, function(key, value){
ct+='<li>';
ct+='<a href="index.html?article_id='+value.get('article_id')+'&type='+value.get('type')+'&serie='+value.get('series')+'#product-detail">Link';
ct+='</a>';
ct+='</li>';
});
ct+='</ul>';
elem.append(ct);
}
}
});
// Returns the View class
return PageView;
});
I follow one of the links from renderRelatedSeriePlainproduct.If I click on the back button on the new page the backInHistory function is called, but the window.history.back(); does not call the backbone router.
Maybe the problem is the #hash in the URL, that is not changed during page transition. But this would not explain, why it works perfectly with my Chrome on my desktop machine. For me it seemed to be a problem of asynchronous calls but even there I could not find a problem.
Maybe it helps to list my router code as well. First of all I was thinking it is an zombie issue in backbone, but I remove all events and views while making the transition.
// function called by the route
// details page
productdetail: function() {
$.mobile.loading("show");
_self = this;
// lazy loading
require([
'collection/ProductDetailCollection',
'collection/RelatedCollection',
'view/ProductDetailView'
],
function(ProductDetailCollection, RelatedCollection, ProductDetailView){
// get URL parameters
var articleID = _self.URLParameter('article_id');
var type = _self.URLParameter('type');
var serie = _self.URLParameter('serie');
// product - details
var productDetail = new ProductDetailCollection.ProductDetail({id: articleID});
// related products
_self.relatedCollectionPlainproduct = new RelatedCollection({serie:serie, type:"Electronics", article_id:articleID});
// assign binded context
productDetail.fetch({
// data fetched
success: function (data) {
// page transition
_self.changePage(new ProductDetailView({
model:data,
relatedCollectionPlainproduct:_self.relatedCollectionPlainproduct
}));
// fetch data
_self.relatedCollectionPlainproduct.fetch({reset:true});
}
});
});
},
// page transition
changePage:function (page) {
// remove previous page from DOM
this.page && this.page.remove() && this.page.unbind();
// assign
this.page = page;
// assign page tag to DOM
$(page.el).attr('data-role', 'page');
// render template
page.render();
// append template to dom
$('body').append($(page.el));
// set transition
var transition = "fade";
// we want to slide the first page different
if (this.firstPage) {
transition = "fade";
this.firstPage = false;
}
// make transition by jquery mobile
$.mobile.changePage($(page.el), {changeHash:true, transition: transition});
// page was rendered - trigger event
page.trigger('render');
$.mobile.loading("hide");
},
I tried to use allowSamePageTransition but with no success. Maybe someone could give me a hint. Thanks!
Looks like jQuery Mobile and Backbone's routers are conflicting. Take a look here:
http://coenraets.org/blog/2012/03/using-backbone-js-with-jquery-mobile/
Thats not the reason. I disabled the routing of jquery mobile.
// Prevents all anchor click handling
$.mobile.linkBindingEnabled = false;
// Disabling this will prevent jQuery Mobile from handling hash changes
$.mobile.hashListeningEnabled = false;

Difference between $(this.el) and this.$el in Backbone

I'm developing a single-page web application using Backbone and Laravel. I've set my router to use pushState and configured Laravel to send all other requests to the main view of the backbone application, where backbone takes care of the routing.
My problem/question is as follows:
I have a route called 'dashboard', this route is the main application view and is shown after login. It uses a collection called Clients.
dashboard:function(uri){
dashboardCallback = function(data){
if(data.check){
console.log('generate dashboard');
//get clients collection
clientsCollection = new Dash.Collections.Clients();
clientsCollection.fetch().then(function(clients){
//genenerate dashboard view
new Dash.Views.Dashboard({collection:clientsCollection}).renderDashboard();
});
}
else{
router.navigate('/', {trigger:true, replace:true});
}
}
Dash.Utilities.user.isLoggedIn(dashboardCallback);
},
The Dash.Views.Dashboard view takes care of all the views in the application, when calling the renderDashboard(); method, it starts rendering all client views. This is where it gets interesting.
The code for rendering all the client views is as follows:
renderClients:function(){
console.log('Rendering all clients', this.collection);
clientsView = new Dash.Views.Clients({collection:this.collection}).render();
$(this.el).html(clientsView.el);
}
with the above code, it works in all cases. With that i mean when I log in first and the application routes me to the dashboard view all the clients gets rendered and appended to the DOM, the same thing happens when I access /dashboard immediately (afther the application checks if i'm logged in).
But, when I use the following code it doesn't load the client views when I first log in. It does load the client views when i access /dashboard directly.
renderClients:function(){
console.log('Rendering all clients', this.collection);
clientsView = new Dash.Views.Clients({collection:this.collection}).render();
this.$el.html(clientsView.el);
}
It took me a while to figure out that the fix of the problem was that I had to replace this.$el with $(this.el), but I alway's thought it didn't matter because they are essentially the same, or am I wrong in this assumption?
Can someone explain to me this weird behaviour?
As requested, here is my global Dashboard view
Dash.Views.Dashboard = Backbone.View.extend({
tagName:'div',
id:'main',
className:'dashboard',
initialize: function(){
console.log('Initializing Global Dashboard View');
//make sure the main element is only added once.
if(!$('.dashboard').length){
$('body').append(this.el);
}
else{
this.el = $('.dashboard');
}
},
renderDashboard: function(){
console.log('Render all Dashboard components');
this.renderNavBar();
this.renderClients();
},
renderNavBar: function(){
var navBarView = new Dash.Views.NavBar().render();
$(this.el).before(navBarView.el);
},
renderLogin: function(){
var logInView = new Dash.Views.Login().render();
$(this.el).html(logInView.el);
},
renderWhoops:function(error){
console.log('Render Whoops from Global Dashboard');
var whoopsModel = new Dash.Models.Whoops(error);
$(this.el).html(new Dash.Views.Whoops({model:whoopsModel}).render().el)
},
renderClients:function(){
console.log('Rendering all clients', this.collection);
clientsView = new Dash.Views.Clients({collection:this.collection}).render();
$(this.el).html(clientsView.el);
}
});
I'd guess that your problem is right here:
if(!$('.dashboard').length){
$('body').append(this.el);
}
else{
this.el = $('.dashboard'); // <----- Broken
}
If there is no .dashboard then you directly assign to this.el and that's a mistake as it won't update this.$el. The result is that this.el and this.$el reference different things and nothing works. You should use setElement to change a view's el:
setElement view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.
So you should be saying this:
if(!$('.dashboard').length){
$('body').append(this.el);
}
else{
this.setElement($('.dashboard')); // <----- Use setElement
}

Backbone routes and view states

Apologies for the possibly poorly formulated title. New to Backbone.
I'm having trouble wrapping my head around how to deal with routes in association with views. Basically I have a view (let's call it ListView) that, depending on its viewMode, renders ItemViews using different templates. It looks something like this:
var ListView = Backbone.View.extend({
// Cache a bunch of templates here
viewMode: 'list', // Default is list
render: function() {
switch(this.viewMode) {
case 'list':
// Render ItemView based on list template
break;
case 'gallery':
// Render ItemView based on gallery template
break;
}
// Render all items in list
this.collection.each(function(model, index) {
new ItemView(); // Maybe pass viewMode as a parameter
});
}
});
My goal is that whenever ListView uses the viewMode "list" or "gallery", this should be reflected in the address bar, and likewise manually entering or clicking a link that leads to e.g. mysite.com/page.html#items/list or #items/gallery should render the same results.
Is there a way of automating this process, or in some other way solve it?
Think your router would be something like:
var yourRouter = Backbone.Router.extend({
routes: {
"items/list": "showList",
"items/gallery": "showGallery"
},
showList: function() {
listView.viewMode = "list"
listView.render();
}
showGallery: function() {
listView.viewMode = "gallery"
listView.render();
}
});
Then in your view events, you can call the navigate method of your router. This will update the address bar.
yourRouter.navigate("items/list")

still the navigate triggers and upate my url, the method is not calling

In my backbone app, i use the requirejs to load the js files. as well i need different views, there is no.of links are there in my drop down menu. according to the drop down menu i a adding the #url example:
http://localhost:85/bino/html/interface-I.html#projectName/project11
the navigate method works fine and updating the url, also whenever i copy and paste this url to any other browser / refresh with current hash state my router methods works fine.
But click on link in the drop down menu not working, the method not calling... what would be the reason and how can i fix this..?
my code: main js file (part of code)
var extender = _.extend({},backBone.Events);
var params ={
boardHolder :$('.boardHolder'),
column :3,
space :30,
extender :extender
};
var listApp = new routerer(params);
backBone.history.start();
extender.bind("list:selected",function(post){
listApp.navigate(post.category+'/'+post.filter);
});
my router code :
define(["backBone","singleton","listCollection","listView","listViews"],function(Backbone,singleton,listCollection,listView,listViews){
singleton.router = Backbone.Router.extend({
routes:{
"" :"appView",
"post" :"postView",
"projectName/:id" :"projectNameView",
"assignedTo/:id" :"assignedToView",
"sortBy/:id" :"sortByView"
},
initialize:function(params){
this.params = params;
this.collection = new listCollection;
console.log('i am called');
},
hashView:function(){
console.log('from hash view');
},
appView:function(){
var that = this;
// var defaultApp = new listCollection();
this.collection.fetch({
success:function(data){
new listViews({model:data,params:that.params})
}
})
},
projectNameView:function(thisView){ // not calling not sync
console.log('called',thisView); // on click not works
},
assignedToView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
},
sortByView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
}
});
return singleton.router;
})
thanks in advance.
navigate only updates the url, you also have to call the route function by setting the trigger option to true. If you'd like to update the URL without creating an entry in the browser's history, also set the replace option to true.
listApp.navigate(post.category+'/'+post.filter);
would become
listApp.navigate(post.category+'/'+post.filter, {trigger: true});

What to be done to prevent the router URL being used directly on the address bar by user?

Have done some working samples using Backbone Router, but is there a way to protect the routes being used directly on the address bar? And also when the user press the back button on the browser, the routes doesn't get cleared and creates issues. What is the best solution for this?
I think I see what you're saying - you want to force the user to enter your site through a certain (home) page. Is that correct?
This is useful, for example, when you're building a mobile-optimized-web-app, and you always want users to enter through a splash screen. What I'll do is set a 'legitEntrance' property to my router, and check for it on every route, as so:
APP.Router = Backbone.Router.extend({
legitEntrance: false,
// Just a helper function
setLegitEntrance: function() {
this.legitEntrance = true;
},
// Send the user back to the home page
kickUser: function() {
this.navigate("home", {trigger:true});
},
routes : {
...
},
// Example router function: Home page
routeToHome: function() {
this.setLegitEntrance();
var homeView = APP.HomeView.extend({ ... });
homeView.render();
},
// Example router function: some other internal page
routeToSomeOtherInternalPage: function() {
if(!this.legitEntrance) {
this.kickUser();
return;
}
var someOtherInternalView = APP.SomeOtherInternalView.extend({
...
});
someOtherInternalView.render();
}
....
});
I'm sure this code could be cleaned up some, but you get the general idea. Hope it helps.

Resources