Computed Properties (Lava.Computed)

Computed Properties in Lava make it possible to create a property on an object whose value is dependent on other properties. Each time a dependent property changes, the computed property will change as well.

A simple example of a computed property is the following, in which we compute the full name using two properties.

var Person = Lava.Object({
    firstName: 'Terry',
    lastName: 'Phillips',
    fullName: Lava.Computed(function () {
        return this.firstName + ' ' + this.lastName;
    })             
});

Accessing the computed property is a bit different than a normal property. To do so, you use the get() method on the property.

var fullName = Person.fullName.get();

Anytime the first or last properties change, it will update any bindings tied to the fullName property. As you can see, there is no need to specify which dependencies to watch for the computed property. Lava can determine which properties the computed property is dependent on automatically, in most cases. If you have a complex dependency, or just want to make certain properties dependencies, Lava allows you to manually declare the dependencies like so:

var Person = Lava.Object({
    firstName: 'Terry',
    lastName: 'Phillips',
    fullName: Lava.Computed('Person.firstName', function () {
        return this.firstName + ' ' + this.lastName;
    })             
});

Last edited Sep 6, 2013 at 8:18 PM by tjscience, version 4

Comments

No comments yet.