Exclude model properties when syncing (Backbone.js)

后端 未结 11 1401
甜味超标
甜味超标 2020-12-07 14:26

Is there a way to exclude certain property from my model when I sync?

For example, I keep in my model information about some view state. Let\'s say I have a picker m

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 14:35

    my solution combine all the above. just use white list instead of black one .. this is good rule in general

    define

              attrWhiteList:['id','biography','status'],
    

    and then overwrite the save

      save: function(attrs, options) {
        options || (options = {});
    
     //here is whitelist or all
        if (this.attrWhiteList != null )
              // Filter the data to send to the server
                 whitelisted =  _.pick(this.attributes, this.attrWhiteList);
        else  
            whitelisted =this.attributes;
        /* it seems that if you override save you lose some headers and the ajax call changes*/
        // get data
        options.data = JSON.stringify(whitelisted);
    
        if ((this.get('id') == 0) || (this.get('id') == null)) 
            options.type = "POST"
        else
            options.type = "PUT";
    
    
        options.contentType = "application/json";
         //        options.headers =  { 
         //            'Accept': 'application/json',
         //            'Content-Type': 'application/json' 
         //        },
    
        // Proxy the call to the original save function
       return  Backbone.Model.prototype.save.call(this, attrs, options);
    },
    

提交回复
热议问题