Skip to content

Instantly share code, notes, and snippets.

@rob-long
Last active December 20, 2019 00:15
Show Gist options
  • Save rob-long/cfdc017550e39425dcfeaf4ffb4a5a4f to your computer and use it in GitHub Desktop.
Save rob-long/cfdc017550e39425dcfeaf4ffb4a5a4f to your computer and use it in GitHub Desktop.
new
import Component from '@ember/component';
import EmberObject, { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
export default Component.extend({
dynamicModelProperty: computed('model', 'subpath', function() {
let subpath = this.subpath;
if (subpath) {
let DynamicClass = EmberObject.extend({
value: alias(`model.${subpath}`)
});
return DynamicClass.create({ model: this.model });
}
return EmberObject.create({});
}),
verbose: computed('dynamicModelProperty.value', function() {
return (
`watching ${this.subpath} with value: ${this.dynamicModelProperty.value} -- known model` +
JSON.stringify(this.model)
);
})
});
import Controller from '@ember/controller';
export default Controller.extend({
appName: 'Dynamic keys',
animals: {
chicken: {
male: 20,
female: 10
},
cow: {
male: 200,
female: 100,
}
pig: {
male: 10,
female: 30
}
},
actions: {
incrementAnimal(type) {
this.set(`animals.${type}.female`, this.get(`animals.${type}.female`) + 1);
console.log('updated model', this.animals);
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<button onclick={{action 'incrementAnimal' 'cow'}}>+cow</button>
<button onclick={{action 'incrementAnimal' 'chicken'}}>+chicken</button>
<button onclick={{action 'incrementAnimal' 'pig'}}>+pig</button>
{{my-component subpath='chicken' model=animals}}
{{my-component subpath='cow' model=animals}}
{{my-component subpath='pig' model=animals}}
<br>
<br>
<h1>Watch {{subpath}}</h1>
<div>subpath: {{subpath}}</div>
<div>verbose: {{verbose}}</div>
{
"version": "0.15.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": "3.4.3",
"ember-template-compiler": "3.4.3",
"ember-testing": "3.4.3"
},
"addons": {
"ember-data": "3.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment