【问题标题】:Uncaught TypeError: Cannot call method 'start' of undefined on Backbone.history.start()未捕获的类型错误:无法调用 Backbone.history.start() 上未定义的方法“开始”
【发布时间】:2012-06-27 01:38:33
【问题描述】:

我正在使用 Rails。我刚刚安装了backbone-rails gem 并按照here 的说明进行操作。

当我尝试执行 Backbone.history.start() 时,我收到此错误:

Uncaught TypeError: Cannot call method 'start' of undefined

根据this other SO question 的说法,我知道在您创建至少一条路线之后才能调用Backbone.history.start()。不过,这似乎不是我的问题,因为我确实有多个路由,在此 CoffeeScript 文件中定义:

class Lunchhub.Routers.RestaurantLocationsRouter extends Backbone.Router
  initialize: (options) ->
    @restaurantLocations = new Lunchhub.Collections.RestaurantLocationsCollection()
    @restaurantLocations.reset options.restaurantLocations

  routes:
    "new"      : "newRestaurantLocation"
    "index"    : "index"
    ":id/edit" : "edit"
    ":id"      : "show"
    ".*"        : "index"

为什么会出现这个错误?

编辑:这是我的代码:

<div id="restaurant_locations"></div>

<script type="text/javascript">
  $(function() {
    window.router = new Lunchhub.Routers.RestaurantLocationsRouter({restaurantLocations: <%= @restaurant_locations.to_json.html_safe -%>});
    Backbone.history.start();
  });
</script>

【问题讨论】:

标签: ruby-on-rails-3 backbone.js


【解决方案1】:

在调用Backbone.history.start之前尝试使用new关键字创建一个路由器实例。

编辑:Backbone.history 必须是 undefined,正如其他人所说,这通常是因为 there needs to be a router 在 Backbone 创建此对象之前至少有一条路由处于活动状态。

Backbone.js 创建一个 Backbone.History 的实例(大写“H”) 一旦控制器被调用,就调用 Backbone.history(小写“h”) 创建的至少指定了一条路线

我看到你正在创建一个新的路由器实例,但问题可能仍然是一个坏的路由器实例,只是与其他问题中讨论的不同——检查typeof你的window.router对象路由器在您拨打Backbone.history.start() 之前。它会返回您所期望的吗?

编辑:正如下面的 cmets 所证实的,RestaurantLocationsRouter 有点糟糕。我们还没有弄清楚原因,但是创建一个新的路由器可以按预期工作,这表明您的路由器实例确实出现了问题。

【讨论】:

  • 我想我已经这样做了,但我可能是错的。我进行了编辑以包含我的代码。
  • 你能检查一下你的 window.router 对象的typeof 看看它返回了什么吗?它可能实际上不是Backbone.Router 的实例。
  • 它看起来像是RestaurantLocationsRouter 的一个实例。它的typeofobject
  • 如果我们要寻找window.router 是否是有效路由器的证据,我可以在控制台中输入window.router.routes,它会返回我所期望的(多条路由)。跨度>
  • 谢谢。我的调试想法已经用完了。顺便说一句,你用的是什么浏览器?
猜你喜欢
  • 1970-01-01
  • 2013-08-31
  • 2011-11-12
  • 2013-09-14
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多