Backbone JS Models and Collection URLs

后端 未结 2 763
傲寒
傲寒 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);
    }
    
    0 讨论(0)
  • 2021-01-30 23:26

    In model

    1. urlRoot is used for the Model.
    2. url is used for the instance of the Model.

    So if urlRoot exists then book.fetch() will fetch the data given id, for example

    var Book = Backbone.Model.extend({urlRoot: 'books' });
    var book = new Book({id: 1});
    book.fetch();  // will get /books/1
    
    var Book = Backbone.Model.extend({});
    var book = new Book({url: 'books/1'});
    book.fetch();  // will get /books/1
    
    
    var Books = Backbone.Collection.extend({model: Book});
    var books = new Books({ /*....*/ });
    books.fetch(); // will get /books/ 
    

    You can refer the backbone Model urlRoot source code here

    I hope it makes sense to you, good luck.

    0 讨论(0)
提交回复
热议问题