Jason Swett
Jason Swett

Reputation: 45094

Uncaught TypeError: Cannot call method 'start' of undefined on Backbone.history.start()

I'm using Rails. I just installed the backbone-rails gem and followed the instructions here.

When I try to do Backbone.history.start(), I get this error:

Uncaught TypeError: Cannot call method 'start' of undefined

I understand that Backbone.history.start() can't be called until after you create at least one route, according to this other SO question. That doesn't seem to be my problem, though, since I do have multiple routes, defined in this CoffeeScript file:

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"

Why am I getting this error?

Edit: here's my code:

<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>

Upvotes: 1

Views: 1941

Answers (1)

buley
buley

Reputation: 29238

Try creating an instance of the router with the new keyword before calling Backbone.history.start.

EDIT: Backbone.history must be undefined, which as others have said is typically because there needs to be a router with at least one route active before Backbone creates this object.

Backbone.js creates an instance of Backbone.History (upper case ‘H’) called Backbone.history (lower case ‘h’) once a controller has been created that has at least one route specified on it

I see you're creating a new instance of the router but it's possible that a bad Router instance is still the issue, just a different flavor than discussed in other issues -- check the typeof your window.router object router before your Backbone.history.start() call. Does it return what you'd expect?

EDIT: As confirmed in the comments below, the RestaurantLocationsRouter is somehow bad. We've yet to figure out why, but creating a new router works as expected and indicates that indeed something has gone awry with your router instance.

Upvotes: 1

Related Questions