Skip to content

Instantly share code, notes, and snippets.

@adamlogic
Forked from givanse/components.foo-bar.js
Last active February 14, 2020 15:05
Show Gist options
  • Save adamlogic/33f6ebbd70255e3754b2308a7ecab0d3 to your computer and use it in GitHub Desktop.
Save adamlogic/33f6ebbd70255e3754b2308a7ecab0d3 to your computer and use it in GitHub Desktop.
Ember runloop demonstration with a computed property and an observer
import Ember from 'ember';
export default Ember.Component.extend({
sourceInternal: 'default',
logs: [],
source: Ember.computed('sourceInternal', {
get: function() {
this._log(`[source getter] sourceInternal=${this.get('sourceInternal')}`);
return this.get('sourceInternal');
},
set: function(key, newSource) {
this._log(`[source setter] sourceInternal=${newSource}`);
return this.set('sourceInternal', newSource);
}
}),
_observeSourceInternal: Ember.observer('sourceInternal', function() {
this._logSource('[observer]');
setTimeout(() => { this._logSource('[delayed]') }, 1000);
}),
_logSource: function(prefix) {
this._log(`${prefix} source=${this.get('source')} sourceInternal=${this.get('sourceInternal')}`);
},
_log: function(log) {
let logs = this.get('logs');
logs.pushObject(log);
},
actions: {
clearLogs: function() {
this.set('logs', []);
}
}
});
body {
margin: 12px 16px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12pt;
}
.flex {
display: flex;
}
.col {
border: 1px solid gray;
border-radius: 8px;
padding: 16px;
margin: 2px;
}
.console {
background-color: #dedede;
min-height: 200px;
border-radius: 4px;
padding: 10px;
line-height: 1.5;
}
source:
{{input value=source}}
<br>
<br>
Change the source value to see how sourceInternal is updated. This demo uses an observer to simulate the behavior I'm seeing in Evergreen, and a delay to show how sourceInternal is updated after the run loop completes.
<br>
<br>
<button {{action "clearLogs"}}>Clear logs</button>
<br>
<br>
<div class="console">
{{#each logs as |str|}}
{{str}}
<br>
{{/each}}
</div>
{
"version": "0.10.4",
"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.18.2",
"ember-template-compiler": "2.18.2"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment