Created
June 21, 2013 18:35
-
-
Save krisselden/5833310 to your computer and use it in GitHub Desktop.
This file contains 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
(function (global) { | |
"use strict"; | |
function empty(obj) { | |
var key; | |
for (key in obj) if (obj.hasOwnProperty(key)) return false; | |
return true; | |
} | |
var Ember = global.Ember, | |
get = Ember.get, set = Ember.set; | |
global.BufferedProxy = Ember.Mixin.create({ | |
buffer: null, | |
hasBufferedChanges: false, | |
unknownProperty: function (key) { | |
var buffer = this.buffer; | |
return buffer && buffer.hasOwnProperty(key) ? buffer[key] : this._super(key); | |
}, | |
setUnknownProperty: function (key, value) { | |
if (!this.buffer) this.buffer = {}; | |
var buffer = this.buffer, | |
content = this.get('content'), | |
current = content && get(content, key), | |
previous = buffer.hasOwnProperty(key) ? buffer[key] : current; | |
if (previous === value) return; | |
this.propertyWillChange(key); | |
if (current === value) { | |
delete buffer[key]; | |
if (empty(buffer)) { | |
this.set('hasBufferedChanges', false); | |
} | |
} else { | |
buffer[key] = value; | |
this.set('hasBufferedChanges', true); | |
} | |
this.propertyDidChange(key); | |
return value; | |
}, | |
applyBufferedChanges: function() { | |
var buffer = this.buffer, | |
content = this.get('content'), | |
key; | |
for (key in buffer) { | |
if (!buffer.hasOwnProperty(key)) continue; | |
set(content, key, buffer[key]); | |
} | |
this.buffer = {}; | |
this.set('hasBufferedChanges', false); | |
}, | |
discardBufferedChanges: function() { | |
var buffer = this.buffer, | |
content = this.get('content'), | |
key; | |
for (key in buffer) { | |
if (!buffer.hasOwnProperty(key)) continue; | |
this.propertyWillChange(key); | |
delete buffer[key]; | |
this.propertyDidChange(key); | |
} | |
this.set('hasBufferedChanges', false); | |
} | |
}); | |
}(this)); |
@kselden just out of curiosity is it possible to use this pattern within a component?
App.MyWidgetComponent = Ember.Component.extend(BufferedProxy, {
// implementation details
});
I have a model instance that is bound to a couple of different components, but buffered proxy isn't quite working for me in that context. When I do the mixin BufferedProxy to my ObjectController it doesn't quite do what I expect because I have delegated some of the form UI to components. If you are curious I can post a JSBin example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you think this should go in a library? I've just used it to help with ember-data. Such a useful bit of code.