nullnullnull
nullnullnull

Reputation: 8189

Only persist data after submit in Ember.js

I'm using Ember.js and Ember-Data. Users can create and update resources, such as the Organization model. For the most part, the system works as expected. One exception is if a user partially fills out a form and then leaves the page without clicking submit. The partially created resource will persist on the client-side. (It's never submitted to the server and so never exists in the database. If the user reloads the page, these partially created resources disappear.)

My routes are fairly standard:

Whistlr.OrganizationsNewRoute = Ember.Route.extend
  model: ->
    @store.createRecord('organization')
  setupController: (controller, model) ->
    controller.set('content', model)

Whistlr.OrganizationEditRoute = Ember.Route.extend
  model: (params) ->
    @store.find('organization', params.organization_id)
  setupController: (controller, model) ->
    controller.set('content', @modelFor('organization'))

Perhaps the behavior I've described is also standard? If so, is there a way to prevent it?

Upvotes: 0

Views: 288

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

You can use the rollback method from DS.Model to revert the local changes.

A good place to use it, is on deactivate method of your route, where you have your form. So when the user exit of the route, the deactivate will be executed, and if have some dirty data, this will be cleaned.

Probally you will need to use the same logic in OrganizationsNewRoute and OrganizationEditRoute, so you can extract to a mixin:

Whistlr.CleanupRecordDataMixin = Ember.Mixin.create({
    deactivate: function() {
        this.get('controller.content').rollback();
    }
});

Whistlr.OrganizationsNewRoute = Ember.Route.extend(Whistlr.CleanupRecordDataMixin, {
   // other methods
});

Whistlr.OrganizationEditRoute = Ember.Route.extend(Whistlr.CleanupRecordDataMixin, {
   // other methods
});

Upvotes: 2

Related Questions