Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js sync() can't find the url property

Tags:

backbone.js

With this contrived example code:

var Product = Backbone.Model.extend({
  idAttribute: '_id',
  url: '/rest/product',
});

var Cart = Backbone.Collection.extend({
  model: Product,
  url: '/rest/cart',
});

p1 = new Product({name: 'Keyboard'});
p2 = new Product({name: 'Mouse'});

c = new Cart();
c.add([p1, p2]);
c.sync();

I see Error: A "url" property or function must be specified There are tons of posts revolving around this same error message, but all the ones I've found are the result of, aptly, not having a url property or function defined somewhere along the way.

I feel as if I've missed a linking step somewhere - maybe I'm implicitly relying on a "magic" connection/callback/property/attribute that Backbone.js doesn't actually set automatically?

like image 850
Chris Tonkinson Avatar asked Jan 24 '13 01:01

Chris Tonkinson


1 Answers

I don't think you should be calling sync directly; I think what you're looking for instead is c.fetch() (or p1.save(); p2.sav2(), depending on which direction you're trying to send data). Sync is just what Backbone uses internally to do its fetch/save (and if you want to change the AJAX details of how it does them, then sync exists for you to overwrite, but otherwise you shouldn't need it).

If you want to conveniently save every model in a collection you can do so with the Underscore built-in-to-Collection method "invoke" (you should be able to do c.save(), but I guess you can't):

 c.invoke('save');
like image 156
machineghost Avatar answered Sep 30 '22 04:09

machineghost