Backbone JS Models and Collection URLs

后端 未结 2 764
傲寒
傲寒 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: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.

提交回复
热议问题