Created
July 24, 2012 15:31
-
-
Save hyperqube/3170680 to your computer and use it in GitHub Desktop.
#emberjs #object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tom = Person.create({ | |
name: "Tom Dale", | |
helloWorld: function() { | |
this.say("Hi my name is " + this.get('name')); | |
} | |
}); | |
tom.helloWorld() // alerts "Hi my name is Tom Dale" | |
var yehuda = Person.create({ | |
name: "Yehuda Katz", | |
say: function(thing) { | |
var name = this.get('name'); | |
this._super(name + " says: " + thing); | |
} | |
}); | |
// Subclassing | |
var LoudPerson = Person.extend({ | |
say: function(thing) { | |
this._super(thing.toUpperCase()); | |
} | |
}); | |
//Reopening Classes and Instances | |
Person.reopen({ | |
isPerson: true | |
}); | |
Person.create().get('isPerson') // true | |
Person = Ember.Object.extend({ | |
// these will be supplied by `create` | |
firstName: null, | |
lastName: null, | |
fullName: function(key, value) { | |
// getter | |
if (arguments.length === 1) { | |
var firstName = this.get('firstName'); | |
var lastName = this.get('lastName'); | |
return firstName + ' ' + lastName; | |
// setter | |
} else { | |
var name = value.split(" "); | |
this.set('firstName', name[0]); | |
this.set('lastName', name[1]); | |
return value; | |
} | |
}.property('firstName', 'lastName') | |
}); | |
var person = Person.create(); | |
person.set('fullName', "Peter Wagenet"); | |
person.get('firstName') // Peter | |
person.get('lastName') // Wagenet | |
// Observers | |
Person = Ember.Object.extend({ | |
// these will be supplied by `create` | |
firstName: null, | |
lastName: null, | |
fullName: function() { | |
var firstName = this.get('firstName'); | |
var lastName = this.get('lastName'); | |
return firstName + ' ' + lastName; | |
}.property('firstName', 'lastName') | |
}); | |
var person = Person.create({ | |
firstName: "Yehuda", | |
lastName: "Katz" | |
}); | |
person.addObserver('fullName', function() { | |
// deal with the change | |
}); | |
person.set('firstName', "Brohuda"); // observer will fire | |
// Because observers are so common, Ember provides a way to define observers inline in class definitions | |
Person.reopen({ | |
fullNameChanged: function() { | |
// this is an inline version of .addObserver | |
}.observes('fullName') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment