Skip to content

Instantly share code, notes, and snippets.

@offirgolan
Created September 20, 2017 19:06
Show Gist options
  • Save offirgolan/1629eb4bbcff54d751e41ad81279f17a to your computer and use it in GitHub Desktop.
Save offirgolan/1629eb4bbcff54d751e41ad81279f17a to your computer and use it in GitHub Desktop.
Buffered Array Proxy
import Ember from 'ember';
const {
get,
computed,
isArray,
A: emberArray
} = Ember;
const BufferedArrayProxy = Ember.ArrayProxy.extend({
buffer: computed('content', function() {
const content = get(this, 'content');
if (isArray(content)) {
return content.toArray();
}
return emberArray();
}).readOnly(),
arrangedContent: computed.alias('buffer'),
hasChanges: computed('buffer.[]', 'content.[]', function() {
return this.hasChanged();
}).readOnly(),
replaceContent() {
get(this, 'buffer').replace(...arguments);
},
applyChanges() {
get(this, 'content').setObjects(this.get('buffer'));
},
discardChanges() {
get(this, 'buffer').setObjects(this.get('content'));
},
hasChanged() {
const content = get(this, 'content');
const buffer = get(this, 'buffer');
const bufferLength = get(buffer, 'length');
const contentLength = get(content, 'length');
if (bufferLength !== contentLength) {
return true;
}
for (let i = 0; i < bufferLength; i ++) {
if (buffer.objectAt(i) !== content.objectAt(i)) {
return true;
}
}
return false;
}
});
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
bufferedArray: BufferedArrayProxy.create({
content: ['a', 'b', 'c']
}),
actions: {
add() {
this.get('bufferedArray').addObject(Math.random());
},
remove(obj) {
this.get('bufferedArray').removeObject(obj);
},
apply() {
this.get('bufferedArray').applyChanges();
},
discard() {
this.get('bufferedArray').discardChanges();
},
replaceContent() {
this.get('bufferedArray').set('content', [
Math.random(),
Math.random(),
Math.random()
])
}
}
});
<h1>Welcome to {{appName}}</h1>
<h3>Original Array</h3>
{{#each bufferedArray.content as |value|}}
<div>
{{value}}
</div>
{{/each}}
<br>
Length: {{bufferedArray.content.length}}
<button {{action 'replaceContent'}}>Replace</button>
<br><br>
<h3>Buffer</h3>
{{#each bufferedArray as |value|}}
<div>
{{value}}
<button {{action 'remove' value}}>x</button>
</div>
{{/each}}
<br>
Length: {{bufferedArray.length}}<br>
Has Changes: {{bufferedArray.hasChanges}}
<br>
<br>
<button {{action 'add'}}>Add</button>
<button {{action 'apply'}}>Apply</button>
<button {{action 'discard'}}>Discard</button>
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment