I’ve looked around at the various tutorials and documentation, and I’m still having some trouble getting the backbone router to work. I’m running the code in my Sites folder on OS X (the url is http://localhost/~plebrun). Neither http://localhost/~plebrun/#foo nor http://localhost/~plebrun/#type/books works. Thoughts?
(Note: the data_* variables contain json data)
/****************************/
/********** MODELS **********/
/****************************/
var Category = Backbone.Model.extend();
var Phrase = Backbone.Model.extend();
/****************************/
/******** COLLECTIONS *******/
/****************************/
var Type = Backbone.Collection.extend({
model: Category
});
/****************************/
/********** VIEWS ***********/
/****************************/
var TypeView = Backbone.View.extend({ /* a Type is a list of Categories */
el: $('#categories'),
initialize: function() {
_.bindAll(this, 'render');
this.render();
},
render: function() {
var ul_list = "";
_(this.collection.models).each(function(category) {
ul_list += '<li><a href="/category/' + category.get('id') + '"><h1>' + category.get('en') + '</h1><p>' + category.get('es') + '</p></a></li>';
});
$(this.el).append(ul_list);
}
});
/****************************/
/********* ROUTER ***********/
/****************************/
var AppRouter = Backbone.Router.extend({
routes: {
"/type/:src": "showType",
"/foo": "foo"
},
locate_data: {
"books": data_books,
"conversations": data_conversations,
"phrases": data_phrases
},
initialize: function() {
_.bindAll(this, 'showType');
},
foo: function() {
alert("foo")
},
showType: function(src) {
console.log(src);
var types = new Type(this.locate_data[src]);
new TypeView({ collection: types });
}
});
/****************************/
/********** INIT ************/
/****************************/
var foo = new AppRouter();
Backbone.history.start({pushState: true, root: "/~plebrun/"});
Turn out routing wasn’t the problem… I had neglected to wrap the code in $(‘document’).ready(). I didn’t think I needed to since the scrip tag reference to the js file was included at the bottom of the web page.