backbone.js use different urls for model save and fetch

前端 未结 4 1754
野性不改
野性不改 2020-12-22 23:44

My back-end has two separate pages, one for handling the model save request and the other for model fetch.

What is the best approach for calling save() and fetch()

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 00:28

    If you have a model and a collection like :-

    MyModel = Backbone.Model.extend({
    
    url: function(){ "API/"
          return "API/MyModel/" +this.get("id");
        }
    });
    
    MyCollection = Backbone.Collection.extend({
        model: MyModel ,
        url: "API/MyModels"
    });
    

    to fetch the collection just call

    MyCollection.fetch({
           success: function(){
           //do something here
           },
           error: function(){
           //Handle your error
           }
    });
    

    To save your model assuming you have the id of the model and you have instantiated your collection (calling it myCollection).

    var model = myCollection .get(id);
       model.save(
                                 model.attributes,
                                    {
                                        success: function (model, response) {
    
                                            //do something on success
                                        },
                                        error: function (model, response) {
                                           //handle the error
                                        }
                                    }
                                );
    

提交回复
热议问题