Skip to content

Instantly share code, notes, and snippets.

@magistrula
Last active March 5, 2019 16:04
Show Gist options
  • Select an option

  • Save magistrula/3481f6112ade39878ffcbda0c3fd76cf to your computer and use it in GitHub Desktop.

Select an option

Save magistrula/3481f6112ade39878ffcbda0c3fd76cf to your computer and use it in GitHub Desktop.
Computed BelongsTo Ids
import Ember from 'ember';
export default Ember.Controller.extend({
store: Ember.inject.service(),
init() {
this._super(...arguments);
const crust1 = this.get('store').createRecord('pizza-crust', {
id: 'crust-1'
});
const crust2 = this.get('store').createRecord('pizza-crust', {
id: 'crust-2'
});
const pizza = this.get('store').createRecord('pizza', {
id: 'pizza-1',
crust: crust1
});
this.setProperties({ pizza, crust1, crust2 });
},
actions: {
toggleCrust() {
if (this.get('pizza.crustId') === this.get('crust1.id')) {
this.set('pizza.crust', this.get('crust2'));
} else {
this.set('pizza.crust', this.get('crust1'));
}
},
removeCrust() {
this.set('pizza.crust', null);
}
}
});
import Ember from 'ember';
const { computed } = Ember;
export default Ember.Mixin.create({
init() {
this._super(...arguments);
this.eachRelationship((name, { kind }) => {
if (kind === 'belongsTo') {
const computedId = computed(name, function() {
return this.belongsTo(name).id();
});
Ember.defineProperty(this, `${name}Id`, computedId);
}
});
}
});
import DS from 'ember-data';
import WithBelongsToIds from 'app/mixins/with-belongs-to-ids';
export default DS.Model.extend(WithBelongsToIds, {
});
import DS from 'ember-data';
import WithBelongsToIds from 'app/mixins/with-belongs-to-ids';
export default DS.Model.extend(WithBelongsToIds, {
crust: DS.belongsTo('pizza-crust'),
toppings: DS.hasMany('pizza-topping')
});
<button {{action "toggleCrust"}}>Toggle Crust</button>
<button {{action "removeCrust"}}>Remove Crust</button>
<p>pizza.id: {{pizza.id}}</p>
<p>pizza.crustId: {{pizza.crustId}}</p>
<p>pizza.crust.Id: {{pizza.crust.id}}</p>
{
"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": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "3.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment