Computed Properties

Dynamic, cached, properties that can return any CFML data type.

Computed Properties are dynamic properties that help derive values from a database or another persistent store, such as a cache.

Computed Properties are similar to Data Properties with some key differences:

  • They are declared as functions within your component with a computed attribute added.

  • They are cached.

  • They can return any CFML data type, not just values that can be parsed by JavaScript like Data Properties.

Computed properties are meant to return values and not change state such as modifying Data Properties. If you need to update a data property, use Actions instead.

Defining Computed Properties

You can define Computed Properties on your components as functions with the computed attribute added.

component extends="cbwire.models.Component" {   
    // Computed properties
    function isEven() computed {
        return data.counter % 2 == 0;
    }

    // Rendering
    function renderIt() {
        return template( "wires.counter" );
    }
}

Accessing Computed Properties

You can access Computed Properties in your component template using propertyName().

<cfoutput>
    <div>
        Is Even: #isEven()#
    </div>
</cfoutput>

You can also access Computed Properties from within your Actions.

component extends="cbwire.models.Component" {   
    // Computed properties
    function isEven() computed {
        return data.counter % 2 == 0;
    }
    
    // Action
    function increment() {
        if ( isEven() ) {
            data.counter += 2;
        } else {
            data.counter += 1;
        }
    }

    // Rendering
    function renderIt() {
        return template( "wires.counter" );
    }

}

Caching

Computed Properties cache their results for the lifetime of the request. It will only execute once if you reference your Computed Property three times in your component template or from within a component action.

// wires/UUID.cfc
component extends="cbwire.models.Component" {   
    // Computed properties
    function getUUID() computed {
        return createUUID();
    }

    // Rendering
    function renderIt() {
        return template( "wires.uuid" );
    }

}
<!--- wires/uuid.cfm -->
<cfoutput>
    <div>
        <p>#getUUID()#</p>
        <p>#getUUID()#</p> <!-- Outputs the same ID because of caching -->
    </div>
</cfoutput>

You can prevent caching on a computed property by passing a false argument when invoking it.

<!--- wires/uuid.cfm -->
<cfoutput>
    <div>
        <p>#getUUID()#</p>
        <p>#getUUID( false )#</p> <!-- Does not have the same ID because caching disabled -->
    </div>
</cfoutput>

Last updated