0

In the back bone docs it specifies that one can link a Model to a collection by passing in the collection as an option when initializing a Model. The model should then be able to build it's own url from the collection.

var MyCollection = Backbone.Collection.extend({
  url: 'api/myitems/'
});

var some_model = Backbone.Model({id:2}, {collection: MyCollection});
var some_model.fetch();

This doesn't work and my console says Error: A "url" property or function must be specified http://localhost/static/backbone-min.js Line 1

Cyclone
  • 1,580
  • 1
  • 8
  • 14
code shogan
  • 839
  • 2
  • 9
  • 25

2 Answers2

2

Some little change are required to achieve whatever you want to achieve.

Model should be declared properly. And the options to the model which you are passing should be passed while initializing the model.

You'l have to initialize the collection and pass collection instance as a parameter to the model instance creation.

var MyCollection = Backbone.Collection.extend({
  url: 'api/myitems/'
});

var SomeModel = Backbone.Model.extend({});

var my_collection = new MyCollection();

var some_model = new SomeModel({ id : 2 }, { collection : my_collection });

var some_model.fetch();

Now it should work.

Checkout the Fiddle.

Cyclone
  • 1,580
  • 1
  • 8
  • 14
  • 3
    The part about the model is not true, you can use `Backbone.Model` as a class. But yeah, the problem comes from the fact that he didn't initialize a collection. – Loamhoof May 23 '13 at 12:27
  • @Loamhoof: oh, didn't know that, does it mean that we can declare backbone `model` like this `var some_model = Backbone.Model({id:2}, {collection: MyCollection});` ? – Cyclone May 23 '13 at 14:22
  • Indeed. I guess I'd never do it but it may be useful in a small app or mayhaps to create singletons... dunno. – Loamhoof May 23 '13 at 16:32
0

You can pass in the model's url as an option when instantiating it.

Make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL. A model with an id of 2, stored in a Backbone.Collection with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/2"

Set the url property (or function) on a collection to reference its location on the server. Models within the collection will use url to construct URLs of their own.

var Notes = Backbone.Collection.extend({
  url: '/notes'
});

// Or, something more sophisticated:

var Notes = Backbone.Collection.extend({
  url: function() {
    return this.document.url() + '/notes';
  }
});
Ashwin Hegde
  • 1,733
  • 4
  • 19
  • 49