未捕获的TypeError:无法在Backbone.history.start()上调用未定义的方法'start'

时间:2012-06-26 15:51:35

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

我正在使用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>

1 个答案:

答案 0 :(得分:1)

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

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

  

Backbone.js创建一个Backbone.History实例(大写'H')   一旦控制器出现,就称为Backbone.history(小写'h')   创建的至少有一个路由指定

我看到你正在创建一个新的路由器实例,但可能是一个坏的路由器实例仍然是问题,只是与其他问题讨论的不同 - 检查typeof你的{{1在window.router电话之前对话路由器。它会回归你所期望的吗?

编辑:正如下面的评论所证实的那样,Backbone.history.start()有点不好。我们还没弄清楚原因,但创建一个新的路由器按预期工作,并表明确实出现了路由器实例的错误。