Skip to content

Instantly share code, notes, and snippets.

@magistrula
Last active June 15, 2018 04:38
Show Gist options
  • Save magistrula/3276e8aa4fdfd9bded9ff7fdfb527c94 to your computer and use it in GitHub Desktop.
Save magistrula/3276e8aa4fdfd9bded9ff7fdfb527c94 to your computer and use it in GitHub Desktop.
Ember Initial Values
import Ember from 'ember';
import withInitialValues from 'app/utils/with-initial-values';
// With the Safe code commented in,
// clicking on the list labeled "Instance 1" or "Instance 2"
// will only result in a change to the clicked list.
//
// With the Unsafe code commented in,
// clicking on the list labeled "Instance 1" or "Instance 2"
// will result in a change to both lists.
//
// Either way, "Instance 3" has a unique array and will not be
// affected by changes to this default array.
export default Ember.Component.extend(
withInitialValues({
// Safe:
words: () => ['apple', 'banana', 'cherry']
}), {
// Unsafe:
// words: ['apple', 'banana', 'cherry'],
click() {
this.get('words').addObject('dragonfruit');
}
});
// Ported from ember-composable-helpers
import { helper } from '@ember/component/helper';
import { A as emberArray } from '@ember/array';
export function array(params = []) {
// slice params to avoid mutating the provided params
return emberArray(params.slice());
}
export default helper(array);
<h2>Instance 1:</h2>
{{my-component}}
<h2>Instance 2:</h2>
{{my-component}}
<h2>Instance 3:</h2>
{{my-component words=(array "foo" "bar" "baz")}}
{{#each words as |word|}}
<div>
{{word}}
</div>
{{/each}}
{
"version": "0.14.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "2.18.2",
"ember-template-compiler": "2.18.2",
"ember-testing": "2.18.2"
},
"addons": {
"ember-data": "2.18.2"
}
}
export default function withInitialValues(initialValues) {
return Ember.Mixin.create({
init() {
this._super(...arguments);
const attrNames = Object.keys(this.attrs);
for (let prop in initialValues) {
const hasAttr = this.hasOwnProperty ?
this.hasOwnProperty(prop) :
attrNames.indexOf(attribute) !== -1;
if (!hasAttr) {
this.set(prop, initialValues[prop]());
}
}
}
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment