Search code examples
extjsextjs3

ExtJS3 - preventing overwriting of models that have not properly loaded


What is the accepted strategy for ensuring that models loaded from a server and then subsequently changed in the UI (i.e. ExtJS) and sent back to the server are saved properly?

The issue we are seeing in an application is that models can be saved without them being properly loaded. This may lead to incomplete models being saved.

e.g. on the server the model has these properties:

color: blue
size: 10
weight: 20

The user loads the model, and during the loading process the user changes

color: red

and saves. As a result, the model loses its weight and size properties on the server. Please note that this is a radical oversimplification of our scenario. The models are much more complex and the amount of data much bigger.

Strategies I can think of:

  1. Ensure everything is loaded before allowing users to save (inelegant, I think).
  2. Keep track of changes in the model, only save the changes. This would not require the model to be fully loaded, as only those things that a user actively edits get saved back to the backend (no idea whether this is supported in ExtJS out of the box).

Can someone point me in the right direction? Could Ext.data.Record.getChanges / isModified be used to implement the 2nd approach? How are deletions handled by ExtJS?


Solution

  • When you need to save a model that has never been saved, you do this:

    model.save();
    

    This method automatically calls the Ext.data.proxy.Proxy.create() method.

    If you need to update the model with some fresh data or even replace the existing data, you do this:

    model.set('property', 'value');
    

    This one, in the other hand, automatically calls the Ext.data.proxy.Proxy.update() method.

    Then you can work with the model class constants referring to the action status:

    • Ext.data.Model.EDIT
    • Ext.data.Model.REJECT
    • Ext.data.Model.COMMIT

    @charris brings a nice example as a comment on the official docs:

    var myStore = Ext.create('Ext.data.Store', {
      model: 'MyApp.model.MyModel',
      listeners: {
        update: function(store, model, operation, eventOptions) {
          if( operation == Ext.data.Model.EDIT ) {
              // Model was edited but not saved...
          }
          else if( operation == Ext.data.Model.COMMIT ) {
              // Model was saved...
          }
        }
      }
    });
    

    Maybe that will help you.