EMBER WORKSHOP: Mixins
Mixins
by jdcravens
HTML
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://builds.emberjs.com/release/ember.js"></script>
JavaScript
// Mixins
//
// for a list of built-in mixins - https://github.com/emberjs/ember.js/tree/master/packages/ember-runtime/lib/mixins
App = Ember.Application.create({});
// Crop Class
var Crop = Em.Object.extend({
name: null
});
// Ore Class
var Ore = Em.Object.extend({
name: null
});
// Farmer Mixin
var Farmer = Ember.Mixin.create({
crop: null,
init: function() {
this._super();
this.set("crop", Crop.create({name: "Potato"}));
}
});
// Miner Mixin
var Miner = Ember.Mixin.create({
ore: null,
init: function() {
this._super();
this.set("ore", Ore.create({name: "Lapis Lazuli Ore"}));
}
});
// BASE CLASS
App.DefaultPlayer = Em.Object.extend({
init: function () {
this.set('imgProfilePrefix', 'default_');
this.set('imgProfileSuffix', '_profile');
},
name: "Steve", // set here instead of passing in create()
imgName: function (imgType) {
return this.get('imgProfilePrefix') + this.get('name').split(' ').join('_').toLowerCase() + this.get('imgProfileSuffix') + '.' + imgType;
}
});
// EXTEND
App.Player = App.DefaultPlayer.extend({
init: function () {
this._super(); // call super, inherit from the base class
this.set('imgProfilePrefix', 'player_');
},
imgName: function (imgType) {
return this._super(imgType); // call super, inherit from the base class
}
});
// CREATING OBJECTS
var steve = App.DefaultPlayer.create({});
//
var jdcravens = App.Player.createWithMixins(Farmer, {
name: "Jesse Cravens",
init: function() {
this._super();
this.get("crop").set("name", "Carrot"); // override a property
}
});
var clearwater = App.Player.createWithMixins(Farmer, Miner, {
name: "Carter Clearwater Cravens"
}); // multiple mixins
console.log(jdcravens.get("name"));
console.log("- crop: " + jdcravens.get("crop.name"));
console.log("- ore: " + jdcravens.get("ore.name")); // undefined ... not a...