Skip to content

Instantly share code, notes, and snippets.

@kalyco
Last active August 29, 2015 14:22
Show Gist options
  • Save kalyco/3fbdb7316465a519dfdb to your computer and use it in GitHub Desktop.
Save kalyco/3fbdb7316465a519dfdb to your computer and use it in GitHub Desktop.
Data binding work is done by observers, that watch for changes, then fire off events (or updates data) when something happens. This change can be responded to in one of two ways.
// 1: Property method
App.NumberController = Ember.ObjectController.extend({
number: 1,
timesTwo: function() {
return Number(this.get('number')) * 2;
}.property('number')
});
// "property" lets you use the return value of a function as if it was a static value.
// if you add "property" to the end of your function and you can bind it to
// your template and display the value there.
// 2: Observe method
App.UserController = Ember.ObjectController.extend({
fullName: function() {
return this.get("first_name") + " " + this.get("last_name");
} property('first_name', 'last_name'),
nameChanged: function() {
console.log('New name! New name!');
} observes.('first_name', 'last_name')
});
//two methods are defined in the Controller.
//the first creates the fullName variable and defines it as a property.
//it is watching both first_name and last_name for changes.
//the second, nameChanged is watching the same two properties but doing it with "observe"
//whenever first_name or last_name change, 2 things are going to happen:
//first, the fullName property is going to update,
//so that anything in the template that's bound to it will reflect those changes.
//in other words, the property method doesn't act on anything,
//it just provides an updated visual to anything that is watching it.
//second, when "observes" sees a change, on the other hand, it's meant to perform an action.
//you can't bind anything to your template that executes 'observes'.
//whatever is executed within the body of the method is all that happens.
//in this case, we're logging to the console that something has updated.
//RULE OF THUMB:
//property is used a lot more often than observes.
//observes is good for when you need something to happen
//beyond just updating other values,
//for example, for form validation logic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment