Reputation: 93
From my understanding the default behavior of Backbone JS Models are to return the Collection's URL, unless the model has a urlRoot
specified. I can't seem to get the behavior to work.
From the documentation:
model.url() ... Generates URLs of the form: "[collection.url]/[id]" by default, but you may override by specifying an explicit urlRoot if the model's collection shouldn't be taken into account.
Here is my collection, and model respectively:
var MyCollection = Backbone.Collection.extend({
model: Model,
initialize: function(options){
this.options = options || {};
},
url: function(){
return "/theurl/" + this.options.param;
}
});
return MyCollection;
...
var MyModel = Backbone.Model.extend({
urlRoot: '/theurl',
initialize: function() {
}
});
return MyModel;
When a model is loaded without a collection, it works great and submits to /theurl
, but when it's loaded into a collection, all methods submit to /theurl/param/
.
If I'm understanding the documentation correctly, the urlRoot
of the Model should override this behavior; and even then the models url should be /theurl/param/{MODEL-ID}
.
Any ideas on what I'm missing/misunderstanding?
...
PS: The model: Model
from the collection is brought in via RequireJS
Upvotes: 9
Views: 12784
Reputation: 755
In the model, try using:
url: function() {
return 'your url goes here';
}
Upvotes: 0
Reputation: 291
UrlRoot should be a function and model must have attributeId
defined.
If you define your model like this all operation will be working if model is in collection or not.
Backbone add modelId
at the end of URL that is returned by urlRoot
function.
var MyModel = Backbone.Model.extend({
attributeId: 'myModelId'
urlRoot: function() {
return '/theurl';
},
initialize: function() {
}
defaults: {
myModelId: null
}
});
Upvotes: 1
Reputation: 2853
It will always use the collection's url even if you have urlRoot
specified.
The reason for urlRoot
is so you can use it in an override, or if the model happens to not be in a collection ( for example maybe it gets removed, but still exists on the client).
So if you want to fetch
or save
the model and override the url generated by the collection you'll need to pass the urlRoot
into these methods explicitly as an option. For example:
yourModel.save({ url: yourModel.urlRoot });
I agree the documentation is confusing and this caught me out recently too.
Upvotes: 9