<< Salesforce week 24 | Home | Using component.find in Salesforce Lightning Components >>

! vs # in Salesforce Lightning Components

Often when you read tutorials on developing Salesforce Lightning components they all contains expressions when passing data and variables into other components. Like say you have an attribute as an array and would like to iterate over the elements:

<aura:attribute name="arr" type="string[]" default="['foo', 'bar', 'baz']" />

<ul class="slds-list--dotted">
<aura:iteration items="{!v.arr}" var="item">
    <li>{!item}</li>
</aura:iteration>
</ul>
Now this is a very simple example but it shows the point. This component shows a simple bullet list with items - when the array attribute ("arr") changes the list will recalculate and update. Often this is what you want but sometimes the array will never change. A better way to do this - especially with arrays as Javascript has not easy / performant way to see if an array actually changed - is to use # instead of ! in your expressions. # means that the expression will not automatically update when the attribute is changed which may speed things up considerably when there are many attributes and many components on the page. Fewer attributes to monitor for changes by the framework leads to better perfornance.
<aura:attribute name="arr" type="string[]" default="['foo', 'bar', 'baz']" />

<ul class="slds-list--dotted">
<aura:iteration items="{#v.arr}" var="item">
    <li>{#item}</li>
</aura:iteration>
</ul>
Another reason for using # instead of ! could be to control the data binding between parent and child components.

There is a nice article on the matter in the Salesforce documentation - Data Binding Between Components.




Add a comment Send a TrackBack