Looking at this example it appears that the router should detect links causing a change in URL that match its routes. However, clicking on the link generated by my Handlebars template only changes the URL and does not trigger the alert in the router. The route is, for some strange reason, triggered upon refresh, though the URL looses the hash.
I'm not sure why the router isn't picking up my URL change. I'd prefer using links rather than Router.navigate if they do work. The route does work for the default route.
The backbone.js code below is run on $(document).ready from a script in the html head.
Item Handlebars template
{{#with lobby}}
<li id="lobby-{{id}}">
<div class="lobby_info">{{name}} - {{owner}} - {{player_count}}/18</div> <a href="#lobby/{{id}}">Join</a>
</li>
{{/with}}
Item Backbone View
var LobbyView = Backbone.View.extend({
events: {
"click .lobby_info": "expand_toggle",
},
expand_toggle: function(evt) {
alert('Expand toggle');
},
render: function() {
var template = Handlebars.compile($("#lobby_template").html());
this.$el.html(template(this.model.toJSON()));
return this;
}
});
Item Collection View
var LobbiesView = Backbone.View.extend({
events: {
"submit #create_lobby_form": "create_lobby",
},
create_lobby: function(evt) {
evt.preventDefault()
var val = $('#lobby_name').val();
socket.emit('create', val);
$("#lobby_name").val("");
},
initialize: function() {
var me = this;
socket.on('create', function(lobby) {
var lobby_item = new LobbyView({
model: new LobbyModel({
lobby: lobby
})
});
// render it to the DOM
el = lobby_item.render().el;
me.$("#lobbies").append(el);
});
},
render: function() {
var me = this;
var template = Handlebars.compile($("#lobbies_template").html());
$(this.el).html(template());
return this;
},
});
Router
var Router = Backbone.Router.extend({
// Match urls with methods
routes: {
"": "index",
"lobby/:lobby_id": "lobby",
"player/:player_id": "player"
},
index: function() {
// connect to the websocket
socket = io.connect();
socket.emit('subscribe');
var view = new LobbiesView({
el: $("#container"),
});
view.render();
},
// View a lobby
lobby: function(lobby_id) {
alert('Viewing lobby' + lobby_id);
},
// View a player
player: function(player_id) {
},
});
// start backbone routing
var app = new Router();
Backbone.history.start({ pushState: true });