Skip to content

Instantly share code, notes, and snippets.

@James-Byrne
Last active May 22, 2019 10:53
Show Gist options
  • Save James-Byrne/861d8de611257c5c316cbd69e5d2fce9 to your computer and use it in GitHub Desktop.
Save James-Byrne/861d8de611257c5c316cbd69e5d2fce9 to your computer and use it in GitHub Desktop.
dynamic computed props and relationships
import Ember from 'ember';
import { defineProperty, computed } from '@ember/object';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
model: null,
init() {
this._super(...arguments);
const relationName = 'test';
this.set('model', this.store.createRecord('myModel'));
defineProperty(this, 'testName', computed(`model.${relationName}`, function() {
return this.model.get(`${relationName}.name`);
}));
defineProperty(this, 'testExists', computed(`model.${relationName}`, function() {
return this.model.belongsTo(relationName).value() !== null;
}));
},
actions: {
addTest() {
const test = this.store.createRecord('test', { name: 'asdf'});
this.model.set('test', test);
},
removeTest() {
this.model.set('test', null);
},
},
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
test: belongsTo('test'),
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
name: attr('string'),
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
{{testName}}
<br>
<br>
it exists: {{if testExists "true" "false"}}
<br>
<br>
<button onclick={{action "addTest"}}>Add</button>
<button onclick={{action "removeTest"}}>Remove</button>
{
"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