6

I am writing directive, that will act like this:

  1. allow editing of some text (using content editable)
  2. on loosing focus it should save its value to model (lately watched and saved to DB)
  3. there should be button "Undo" which revert changes.

My implementation is: http://plnkr.co/edit/DsWEYQV4j51i4GO6KjSe?p=preview

The only problem I have is when I press "undo" button, DIV lose focus (so 'focusout' event is fired) and value is saved in model, so "undo" button can't revert its value.

( I click "undo" -> focusout event (autosave) -> click event (??? can't revert) )

Possible workarounds I see:

  1. set timeout on blur and cancel it if 'undo' button was pressed. But it is ugly as user can enter value and navigate to other part of app, so timeouted saving won't run any $watch listeners.
  2. save value on focusin and restore it when 'undo' button is saved. This cause another problem: $watch listeners would run with changed value and then run again with previous value (so there would be 2 writes to DB instead of one)

Do anybody have solution for such behaviour (autosave on blur + undobutton)?

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59
  • 1
    I think you're going to have to live with two DB writes (workaround #2). Since you can't know if the user is going to hit 'Undo', you have to save the changed value first, if you need autosave behavior. Hopefully, undo operations will be rare, and hence so will the double DB writes. – Mark Rajcok Mar 28 '13 at 18:09
  • Did you see this?? http://stackoverflow.com/questions/13320015/how-to-write-a-debounce-service-in-angularjs Could help you with the autosave – Javier Constanzo Oct 15 '13 at 16:32

1 Answers1

1

How about using underscore.js debounce function or similar to cause a delay on autosave, where it will check for a undo flag and cancel? Not sure what the $watch listeners are doing. Of course it will still not work if the user completely goes out of the app or refreshes the page etc.

Ketan
  • 5,861
  • 3
  • 32
  • 39