Thursday, March 31, 2016

EXTJS: sync operation multiple requests fired

Let me start with an example. Here is my sample model.

Ext.define('ExampleApp.model.Property', {
    extend: 'Ext.data.Model',
    idProperty: 'name',
    fields: [
        {name: 'name', type: 'string'},
        {name: 'value', type: 'string'}
    ],
    autoLoad: false,
    proxy: {
        type: 'rest',
        url: {sampleURL},
        batchActions: true, //batch all requests into one request
        reader: {
            type: 'json',
            rootProperty: ''
        },
        writer: {
            type: 'json',
            encode: false,
            writeAllFields: true,
            allowSingle: false //even if single object send it as an array
        }
    }
});

Here is my sync operation:

 var store = this.getExampleStore();  
 var newRecord = Ext.create('ExampleApp.model.Property');  
 var propertyName = rec.name;  
 var propertyValue = rec.value;  
 newRecord.set("name", propertyName);  
 newRecord.set("value", propertyValue);  
 store.add(newRecord);  
 store.sync({  
   success: function(batch, operations){  
      Ext.msg.Alert("store sync successful");  
   },  
   failure: function(batch, operations){  
      store.rejectChanges();  
   }  
 });  

To avoid the multiple requests for sync to be fired, here is the fix:
 batchActions: true 

This one config will not allow multiple requests to be fired. But all the new records added would be sent as a single request. But, what if you want only the last added record to be sent to the server. Consider this scenario: The record first added may have failed. You change the record data and add it to the store again. batchActions: true will send all the records as a batch. So all the previous records will also be sent.
 store.rejectChanges(); 


In the failure callback method of the sync operation, I called the above method, that removes all the records added till now. Hence only 1 record in the store remains to be sent to the server.

Happy coding :)

No comments:

Post a Comment