Skip to content

Instantly share code, notes, and snippets.

@k-fish
Last active November 23, 2016 19:07
Show Gist options
  • Save k-fish/852d9e7710715344b524822108699bd8 to your computer and use it in GitHub Desktop.
Save k-fish/852d9e7710715344b524822108699bd8 to your computer and use it in GitHub Desktop.
didReceiveAttrs attribute helper example
import Ember from 'ember';
import { attrDidInitOrUpdate, getAttrValue } from 'app/utils/attr-helper';
const { run } = Ember;
export default Ember.Component.extend({
didReceiveAttrs({ oldAttrs, newAttrs }) {
this._super(...arguments);
const fooChanged = attrDidInitOrUpdate('foo', oldAttrs, newAttrs);
const barChanged = attrDidInitOrUpdate('bar', oldAttrs, newAttrs);
if (fooChanged) {
console.log('foo changed');
console.log(getAttrValue('foo', oldAttrs));
console.log(getAttrValue('foo', newAttrs));
}
if (barChanged) {
console.log('bar changed');
console.log(getAttrValue('bar', oldAttrs));
console.log(getAttrValue('bar', newAttrs));
}
run.later(this, function() {
this.getAttr('updateFoo')();
}, 1000);
run.later(this, function() {
this.getAttr('updateBar')();
}, 4000);
}
});
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
actions: {
updateFooAndBar() {
this.set('foo', '123');
this.set('bar', '456');
}
}
});
{{example-component
foo=foo
bar=bar
updateFoo=(action (mut foo) '123')
updateBar=(action (mut bar) '456')
}}
<h1>Example component</h1>
Foo: {{foo}} <br/>
Bar: {{bar}} <br/>
{
"version": "0.10.6",
"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.9.0",
"ember-data": "2.9.0",
"ember-template-compiler": "2.9.0",
"ember-testing": "2.9.0"
},
"addons": {}
}
const { get } = Ember;
export function getAttrValue(key, attrs) {
return get(attrs || {}, `${key}.value`);
};
export function attrDidInit(key, oldAttrs, newAttrs) {
return !oldAttrs && getAttrValue(key, newAttrs);
};
export function attrDidUpdate(key, oldAttrs, newAttrs) {
return getAttrValue(key, oldAttrs) !== getAttrValue(key, newAttrs);
};
export function attrDidInitOrUpdate(key, oldAttrs, newAttrs) {
return attrDidInit(...arguments) || attrDidUpdate(...arguments);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment