Last active
December 18, 2015 12:39
-
-
Save mitchlloyd/5784462 to your computer and use it in GitHub Desktop.
(Blog snippet) A mixin for autosaving.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#= require ./debounce | |
BUFFER_DELAY = 1000 | |
App.AutoSaving = Ember.Mixin.create | |
# Setup buffers to write to instead of directly editing | |
# the model attributes. | |
_buffers: Ember.Map.create() | |
# Buffered fields are saved after the set delay for the | |
# debounce | |
bufferedFields: [] | |
# InstaSave fields save the model as soon as they are changed | |
instaSaveFields: [] | |
# Convenience property to access all the fields together | |
_allFields: (-> | |
@get('bufferedFields').concat @get('instaSaveFields') | |
).property() | |
# If we update a field that has been specified as one of the | |
# bufferedFields or instaSaveFields write these to a buffer | |
# instead of the actual attribute and save. | |
setUnknownProperty: (key, value) -> | |
if @get('bufferedFields').contains(key) | |
@get('_buffers').set(key, value) | |
@_debouncedSave() | |
else if @get('instaSaveFields').contains(key) | |
@_super(key, value) | |
@_debouncedSave(now: true) | |
else | |
@_super(key, value) | |
# Pull properties from the buffer if they have been set there. | |
unknownProperty: (key) -> | |
if @get('_allFields').contains(key) and @_buffers.get(key) | |
@_buffers.get(key) | |
else | |
@_super(key) | |
# Write the buffers to the actual content and save. | |
_autoSave: -> | |
if not @get('content.isSaving') | |
@get('_buffers').forEach (key, value) => | |
@get('content').set(key, value) | |
@get('content').save() | |
else # If we're currently saving, then try to save later. | |
@_debouncedSave() | |
_debouncedSave: App.debounce (-> @_autoSave()), BUFFER_DELAY | |
# When the model is about to change out from under the controller we must | |
# immediately save any pending changes and clear out the buffers. | |
_saveNowAndClear: (-> | |
return unless @get('content') | |
@_debouncedSave(now: true) | |
@set('_buffers', Ember.Map.create()) | |
).observesBefore('content') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment