BackboneJS model.url using collection.url

好久不见. 提交于 2019-12-04 02:59:53

问题


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


回答1:


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.




回答2:


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
    }
});



回答3:


In the model, try using:

url: function() {
    return 'your url goes here';
}


来源:https://stackoverflow.com/questions/17461264/backbonejs-model-url-using-collection-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!