Undefined is not a function in Backbone.js

2019-07-13 11:35发布

问题:

I get the error "undefined is not a function" when running this code locally and from a Dropbox public url, http://dl.dropbox.com/u/6862628/backbone.html.

However, when I run it on jsfiddle it works as expected: http://jsfiddle.net/fdKKD/

In short, I'm creating a simple model and a simple view. When I set a property on the model, the view console.log's "render".

I'm seeing the same behavior in Chrome 17 and Safari, Mac.

This is driving me nuts. Would appreciate some help.

回答1:

Backbone requires either jQuery or Zepto to be loaded before Backbone if you intend to do any DOM manipulation (i.e. if you use a view). Your HTML includes things in this order:

  1. Underscore.
  2. Backbone.
  3. jQuery.

So Backbone doesn't know if it should use jQuery or Zepto when it loads and you end up with an undefined value being used a function. Your original jsfiddle uses jQuery in the sidebar so jQuery will be loaded by jsfiddle before your <script> tags are hit, so Backbone sees jQuery, uses it, and everything works. If you switch to "No-Library (pure JS)":

http://jsfiddle.net/ambiguous/pzgW7/

then you'll see your error again. If you include jQuery first:

http://jsfiddle.net/ambiguous/C32Gd/

things will work.