ironchamber
ironchamber

Reputation: 204

Backbone.js fetch() ajax error

I am putting together a basic CRUD system for a project, and we've decided to bundle in Backbone.js & CoffeeScript to abstract more of our JavaScript functionality. The learning curve has been pretty steep for me, since I'm not much of a JS pro.

At the moment, I'm just trying to pull a record. Any record. So I've rigged a dummy route to supply a 'products' record set via JSON, to see how it renders, before I go forward.

  window.Product = Backbone.Model.extend
    initialize: -> console.log this
  window.Products = Backbone.Collection.extend
    model: Product
    initialize: -> console.log this
    url: '/dummy'

So, in the console, I type:

product = new Product()

And it seems to render the product just fine. But when I type:

product.fetch()

It returns:

TypeError: Cannot call method 'ajax' of undefined

I tried the same thing with the Collection.

products = new Products()
products.fetch()
TypeError: Cannot call method 'ajax' of undefined

I've made other parts (view renders, etc.) work just fine, but this ajax error is getting at me repeatedly. I've spent hours looking through different documentation (including the official ones, and all the information I could trail to from the wiki), trying out the code in plain JavaScript as well as CoffeeScript, implementing different scopes (with/without window namespacing), etc. There's nothing on Google.

This must be something ridiculously simple that I should probably just know, but I can't figure it out for the life of me. Or it was the one spot of the documentation that I missed. Can anyone tell me what I'm doing wrong?

Upvotes: 2

Views: 1504

Answers (2)

Evan Moran
Evan Moran

Reputation: 4173

The other solution is to call this at document ready:

Backbone.setDomLibrary(jQuery); 

This way the file include order doesn't matter.

Upvotes: 2

Elf Sternberg
Elf Sternberg

Reputation: 16381

@Ironchamber: In order to use the Ajax method of Backbone, you must also supply a library that provides cross-browser Ajax support. Backbone is optimized to use either jQuery or Zepto. It looks to me from your error message that you're missing one of those.

Upvotes: 8

Related Questions