Backbone JS Models and Collection URLs

后端 未结 2 762
傲寒
傲寒 2021-01-30 22:51

If I have a model named \"Book\" and a collection named \"Library\" defined as below:

Book

app.Book = Backbone.Model.extend({
    defaults: {
        tit         


        
2条回答
  •  别那么骄傲
    2021-01-30 23:18

    Basically, there are 3 possibilities to construct a model's url:

    • If the model object exists in a collection then its url method will return an address composed of the collection.url and model.id: [collection.url]/[id].

    • If you don't want to use a model inside the collection, then model.urlRoot's value can be used instead of the collection.url fragment, resulting in the following pattern: [urlRoot]/[id].

    • Finally, if you're NOT planning to persist more that one model of a given type to the server or will be defining URLs for each model upon their creation, you can directly assign a value to model.url.

    Collections send only GET requests — to get an array of models' JSON data. For saving, removing, and updating, the individual model's save() (POST/PUT/PATCH) and destroy() (DELETE) methods are used.

    Here's the source code of Backbone.Model.url, which should help you:

    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    }
    

提交回复
热议问题