Skip to content

Instantly share code, notes, and snippets.

@LudoBermejo
Last active October 6, 2016 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LudoBermejo/0ae0f366111739cd2b3cd5231082abb7 to your computer and use it in GitHub Desktop.
Save LudoBermejo/0ae0f366111739cd2b3cd5231082abb7 to your computer and use it in GitHub Desktop.
New Twiddle

EmberJS Classes Example #5

An example of shared properties

If you extend an Embed Object with a public property, the value property will be the same for all the clindren. To avoid this, you should use init in the parent class to initialize the property.

import Ember from 'ember'
// Example of implementation with public property (BAD)
const SkywalkerFamily = Ember.Object.extend( {
name: "Anakin",
friends: []
})
const anakinSkyWalker = SkywalkerFamily.create ( {
name: "Anakin"
})
anakinSkyWalker.friends.pushObject("Obi wan");
anakinSkyWalker.friends.pushObject("Kitster Chanchani Banai");
const lukeSkyWalker = SkywalkerFamily.create ( {
name: "Luke",
})
lukeSkyWalker.friends.pushObject("Han Solo");
lukeSkyWalker.friends.pushObject("Chewaka");
// Good implementation. Put the property in the init.
SkywalkerFamily.reopen({
init() {
this.set('enemies', []);
}
});
const anakinSkyWalker2 = SkywalkerFamily.create ( {
name: "Anakin"
})
anakinSkyWalker2.enemies.pushObject("Darth Maul");
anakinSkyWalker2.enemies.pushObject("Count Dooku");
const lukeSkyWalker2 = SkywalkerFamily.create ( {
name: "Luke"
})
lukeSkyWalker2.enemies.pushObject("Darth Vader");
lukeSkyWalker2.enemies.pushObject("Jabba");
export default Ember.Controller.extend({
anakin: anakinSkyWalker,
luke: lukeSkyWalker,
anakin2: anakinSkyWalker2,
luke2: lukeSkyWalker2
});
<h1>Shared use of public property</h1>
List of friends of {{anakin.name}}
<ul>
{{#each anakin.friends as |friend|}}
<li>{{friend}}</li>
{{/each}}
</ul>
List of friends of {{luke.name}}
<ul>
{{#each luke.friends as |friend|}}
<li>{{friend}}</li>
{{/each}}
</ul>
<h1>Alternative instantiation of shared public property</h1>
List of enemies of {{anakin2.name}}
<ul>
{{#each anakin2.enemies as |enemy|}}
<li>{{enemy}}</li>
{{/each}}
</ul>
List of friends of {{luke2.name}}
<ul>
{{#each luke2.enemies as |enemy|}}
<li>{{enemy}}</li>
{{/each}}
</ul>
{
"version": "0.10.5",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.8.0",
"ember-data": "2.8.0",
"ember-template-compiler": "2.8.0",
"ember-testing": "2.8.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment