0

我在前往路线时无法触发“刽子手”功能

应用程序.js

var init = function(){
  console.log("init called");      #logged
  var router = new Router();
  console.log(router);
  Backbone.history.start();
};

当我检查 console.log(router) 中的“路由器”变量时,它表明在路由器对象上创建了 hangman 函数

child
__proto__: ctor
constructor: function (){ return parent.apply(this, arguments); }
hangman: function () {
routes: Object
/hangman: "hangman"
__proto__: Object
__proto__: Object

但是,当我导航到 localhost:3000/hangman 时,没有调用警报。你能建议我可能做错了什么吗?我在 Rails 应用程序中使用主干。我不太明白 Backbone 是如何理解 Rails 路由的,因为 localhost:3000/hangman 是在我的 rails 路由器文件中定义的。我想我可能必须执行 localhost:3000/hangman/#hangman 才能激活主干路由(与 rails 路由无关),但这也不起作用。

路由器.js

$(function() {

  window.Router = Backbone.Router.extend({

    routes: {
    '/hangman' : 'hangman'
  },

    hangman: function() {
      console.log("hangman called");      #never logged
      alert("hangman");
  }

  });

});
4

1 回答 1

0

来自精美Router#extend手册

延长 Backbone.Router.extend(properties, [classProperties])

[...] 请注意,您需要避免在路由定义中使用前导斜杠:

您可能也对该pushState选项感兴趣:

start Backbone.history.start([options])
[...]
要表明您希望pushState在应用程序中使用 HTML5 支持,请使用Backbone.history.start({pushState: true}).

所以首先修复你的路线:

routes: {
    'hangman' : 'hangman' // No more leading slash.
}

然后使用pushState: trueget /hangman( 而不是/#hangman) 工作:

Backbone.history.start({ pushState: true });

于 2013-01-06T20:33:11.457 回答