Skip to content

Instantly share code, notes, and snippets.

@2hu12
Last active February 3, 2020 13:45
Show Gist options
  • Save 2hu12/bd7123e5baa84e95ed31253e13885135 to your computer and use it in GitHub Desktop.
Save 2hu12/bd7123e5baa84e95ed31253e13885135 to your computer and use it in GitHub Desktop.
computed property
import Ember from 'ember';
import { computed, set, setProperties } from '@ember/object';
import { observer } from '@ember/object';
import { filterBy } from '@ember/object/computed';
let list = [1,2,3];
let listOfObj = [{name: 'foo', age: 1}, {name: 'bar', age: 2}];
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
list,
listOfObj,
nameIsDoo: filterBy('listOfObj', 'name', 'doo'),
foo: computed('list', function() {
return {
bar: {
open: false,
list: this.get('list'),
}
}
}),
aa: 'aa',
bb: computed('aa', {
get() {
return {
aa: this.get('aa') + '_b',
};
},
set(key, value) {
console.log(key, value);
let [aa] = value.split('_');
this.set('aa', aa);
return value;
}
}),
_bb: observer('bb.aa', function() {
console.log('bb changed', this.get('bb'));
}),
init() {
this._super(...arguments);
const foo = [false, false, false, false];
setProperties(this, {
foo
});
},
actions: {
toggleOpen() {
// this.set('foo.bar.open', true);
this.toggleProperty('foo.bar.open');
},
changeName(obj) {
let result = this.listOfObj.findBy('name', obj.name);
// set(result, 'name', 'doo');
setProperties(result, {
name: 'doo'
});
},
replaceObjItem(i, obj) {
set(obj, 'name', 'doo');
this.foo.replace(i, 1, [obj]);
},
replaceItem(i) {
this.foo.replace(i, 1, ['a']);
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
{{aa}} {{bb.aa}} <button {{action (mut bb.aa) "cc_b"}}>mut</button>
<br>
<br>
{{foo.bar.open}}
<button {{action "toggleOpen"}}>toggle</button>
<br>
<br>
{{#each listOfObj as |obj idx|}}
<li>{{obj.name}} --- {{obj.age}} <button {{action "changeName" obj}}>changeName</button> <button {{action "replaceObjItem" idx obj}}>replaceName</button></li>
{{/each}}
name is doo length: {{nameIsDoo.length}}
{{#each foo as |item idx|}}
{{item}} <button {{action "replaceItem" idx}}>replace</button>
{{/each}}
<br>
<br>
{
"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