Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot call method 'extend' of undefined

I am trying to get a CoffeeScript class to extend a Backbone.Model. I built a brand new rails 3.1 app, created a scaffold of 'Stone', with 3 attributes, and patched a snippet of the Todos.coffee example into stones.js.coffee. I have both backbone.js and underscore.js in the app/assets/javascripts folder. When I run this under the Chrome Java console, I get the message above in the console log. Any ideas?

Actual code follows:

$ -> 

  class Todo extends Backbone.Model
    # Default attributes for the todo.
    defaults:
     content: "empty todo..."
     done: false

    # Ensure that each todo created has `content`.
    initialize: ->
      if !@get("content")
      @set({ "content": @defaults.content })

    # Toggle the `done` state of this todo item.
    toggle: ->
      @save({ done: !@get("done") })

    # Remove this Todo from *localStorage* and delete its view.
    clear: ->
      @destroy()
      @view.remove()

The application.js being used is what was generated by Rails 3.1. I copied the backbone.js and underscore.js from the Todos github repo, https://github.com/JasonGiedymin/backbone-todojs-coffeescript

like image 780
explainer Avatar asked Dec 05 '22 18:12

explainer


1 Answers

The problem is simply that underscore.js is being loaded after backbone.js, when it's a prereq that has to be loaded before. (Notice in the Backbone.js source that it sets var _ = root._ immediately, so even if a global _ is declared later, it's not visible from Backbone's scope.) Sprockets loads the JS files in your assets directory in alphabetical order by default.

You can fix this using Sprockets: Put

//= require underscore.js

before

//= require_tree .

to ensure that it's loaded first.

like image 158
Trevor Burnham Avatar answered Dec 07 '22 07:12

Trevor Burnham