查看此示例,路由器似乎应该检测导致与其路由匹配的 URL 更改的链接。但是,单击我的 Handlebars 模板生成的链接只会更改 URL,不会触发路由器中的警报。出于某种奇怪的原因,该路由在刷新时触发,尽管 URL 丢失了哈希值。
我不确定为什么路由器没有接收到我的 URL 更改。如果它们确实有效,我更喜欢使用链接而不是 Router.navigate。该路由确实适用于默认路由。
下面的主干.js 代码在 $(document).ready 上运行,来自 html 头中的脚本。
项目车把模板
{{#with lobby}}
<li id="lobby-{{id}}">
<div class="lobby_info">{{name}} - {{owner}} - {{player_count}}/18</div> <a href="#lobby/{{id}}">Join</a>
</li>
{{/with}}
项目主干视图
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;
}
});
项目集合视图
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;
},
});
路由器
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 });