Uncaught TypeError: Cannot call method 'extend' of undefined

天涯浪子 提交于 2019-12-10 17:11:36

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/8762169/uncaught-typeerror-cannot-call-method-extend-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!