Skip to content

Instantly share code, notes, and snippets.

@piotrpalek
Created August 9, 2017 14:26
Show Gist options
  • Save piotrpalek/6eb2e30136ca059c71e2631b47ab5ca2 to your computer and use it in GitHub Desktop.
Save piotrpalek/6eb2e30136ca059c71e2631b47ab5ca2 to your computer and use it in GitHub Desktop.
latest change CP
import Ember from 'ember';
function latestProperty(dependentKeyA, dependentKeyB, latestWin = false) {
let aTimestamp, bTimestamp;
aTimestamp = bTimestamp = + new Date();
let aCache, bCache;
return Ember.computed(dependentKeyA, dependentKeyB, function() {
let currentA = Ember.get(this, dependentKeyA);
let currentB = Ember.get(this, dependentKeyB);
let timestamp = + new Date();
if (currentA !== aCache) {
aCache = currentA;
aTimestamp = timestamp;
}
if (currentB !== bCache) {
bCache = currentB;
bTimestamp = timestamp;
}
if (aTimestamp === bTimestamp) {
return latestWin ? dependentKeyA : dependentKeyB;
} else if (aTimestamp > bTimestamp) {
return dependentKeyA;
} else {
return dependentKeyB;
}
});
}
function latestValue(dependentKeyA, dependentKeyB, latestWin = false) {
let aTimestamp, bTimestamp;
aTimestamp = bTimestamp = + new Date();
let aCache, bCache;
return Ember.computed(dependentKeyA, dependentKeyB, function() {
let currentA = Ember.get(this, dependentKeyA);
let currentB = Ember.get(this, dependentKeyB);
let timestamp = + new Date();
if (currentA !== aCache) {
aCache = currentA;
aTimestamp = timestamp;
}
if (currentB !== bCache) {
bCache = currentB;
bTimestamp = timestamp;
}
if (aTimestamp === bTimestamp) {
return latestWin ? currentA : currentB;
} else if (aTimestamp > bTimestamp) {
return currentA;
} else {
return currentB;
}
});
}
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
valueA: 'aaaa',
valueB: 'bbbb',
latestChangeValue: latestValue('valueA', 'valueB'),
latestChangeProperty: latestProperty('valueA', 'valueB')
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
Value A: {{input value=valueA}}
<br>
<br>
Value B: {{input value=valueB}}
<br>
<br>
Latest value comes from: {{latestChangeProperty}}
<br>
and is equal to: {{latestChangeValue}}
{
"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