Binding in Aurelia!!
Databinding
HTML & SVG Attributes
- Aurelia supports binding HTML and SVG attributes to JavaScript expressions.
- Attribute binding declarations have three parts: attribute.command="expression".
attribute: an HTML or SVG attribute name.
command: one of Aurelia's attribute binding commands:
one-time: flows data one direction: from the view-model to the view, once.
to-view / one-way: flows data one direction: from the view-model to the view.
from-view: flows data one direction: from the view to the view-model.
two-way: flows data both ways: from view-model to view and from view to view-model.
bind: automically chooses the binding mode.
Uses two-way binding for form controls and to-view binding for almost everything else.
Uses the default binding. One-way binding for everything but form controls, which use two-way binding
expression: a JavaScript expression.
command: one of Aurelia's attribute binding commands:
one-time: flows data one direction: from the view-model to the view, once.
to-view / one-way: flows data one direction: from the view-model to the view.
from-view: flows data one direction: from the view to the view-model.
two-way: flows data both ways: from view-model to view and from view to view-model.
bind: automically chooses the binding mode.
Uses two-way binding for form controls and to-view binding for almost everything else.
Uses the default binding. One-way binding for everything but form controls, which use two-way binding
expression: a JavaScript expression.
- Consider using one-time
in performance critical situations where the data never changes because
it skips the overhead of observing the view-model for changes.
At the moment inheritance of bindables is not supported. For use cases where class B extends A and B is used as custom Element/Attribute @bindable properties cannot be defined only on class A. If inheritance is used, @bindable properties should be defined on the instantiated class.
DOM Events
- The binding system supports binding to DOM events.
- A DOM event binding will execute a JavaScript expression whenever the specified DOM event occurs.
- The $event value can be passed as an argument to a delegate or trigger function call if you need to access the event object.
- A DOM event binding will execute a JavaScript expression whenever the specified DOM event occurs.
- The $event value can be passed as an argument to a delegate or trigger function call if you need to access the event object.
- Event binding declarations have three parts: event.command="expression".
event: the name of a DOM event, without the "on" prefix.
command: one of Aurelia's event binding commands:
trigger: attaches an event handler directly to the element. When the event fires, the expression will be invoked.
delegate: attaches a single event handler to the document (or nearest shadow DOM boundary) which handles all events of the specified type in bubbling phase, properly dispatching them back to their original targets for invocation of the associated expression.
capture: attaches a single event handler to the document (or nearest shadow DOM boundary) which handles all events of the specified type in capturing phase, properly dispatching them back to their original targets for invocation of the associated expression.
expression: a JavaScript expression. Use the special $event property to access the DOM event in your binding expression.
command: one of Aurelia's event binding commands:
trigger: attaches an event handler directly to the element. When the event fires, the expression will be invoked.
delegate: attaches a single event handler to the document (or nearest shadow DOM boundary) which handles all events of the specified type in bubbling phase, properly dispatching them back to their original targets for invocation of the associated expression.
capture: attaches a single event handler to the document (or nearest shadow DOM boundary) which handles all events of the specified type in capturing phase, properly dispatching them back to their original targets for invocation of the associated expression.
expression: a JavaScript expression. Use the special $event property to access the DOM event in your binding expression.
DOM Event Binding Examples
<template>
<template>
<button type="button" click.trigger="cancel()">Cancel</button>
<button type="button" click.delegate="select('yes')">Yes</button>
<button type="button" click.delegate="select('no')">No</button>
<input type="text" blur.trigger="elementBlurred($event.target)">
<input type="text" change.delegate="lastName = $event.target.value">
</template>
The cancel button uses the trigger command
to attach an event listener to the button element that will call the
view-model's cancel method. The yes and no buttons use the delegate command which will use the event delegation pattern. The input elements have binding expressions that use the special $event property to access the DOM event .
Aurelia will automatically call preventDefault() on events handled with delegate or trigger binding. Most of the time this is the behavior you want. To turn this off, return true from your event handler function
Your custom element or attribute can invoke the function that was passed to the @bindable property using standard call syntax: this.go();.
If you need to invoke the function with arguments, create an object
whose keys are the argument names and whose values are the argument
values, then invoke the function with this "arguments object". The
object's properties will be available for data-binding in the call binding expression. For example, invoking the function with this.go({ x: 5, y: -22, z: 11})) will make x, y & z available for binding
Accessing the call argument properties
<my-element execute.call="doSomething(x, y)"></my-element>
Aurelia will automatically call preventDefault() on events handled with delegate or trigger binding. Most of the time this is the behavior you want. To turn this off, return true from your event handler function
Function References
- While developing custom elements or custom attributes you may encounter a situation where you have a @bindable property that expects a reference to a function.
- Use the call binding command to declare & pass a function to the bindable property.
- The call command is superior to the bind command for this use-case because it will execute the function in the correct context, ensuring this is what you expect it to be.
Simple call binding
<template>
<button my-attribute.call="sayHello()">Say Hello</button>
</template>
<my-element go.call="doSomething()"></my-element>
<input type="text" value.bind="taskName">
<my-element go.call="doSomething(taskName)"></my-element>
Accessing the call argument properties
<my-element execute.call="doSomething(x, y)"></my-element>
Referencing Elements
- Use the ref binding command to create a reference to a DOM element.
- The ref command's most basic syntax is ref="expression".
- When the view is data-bound the specified expression will be assigned the DOM element.
- Creates a reference to an HTML element, a component/a component's parts
ref="someIdentifier" or element.ref="someIdentifier" - Create a reference to the HTMLElement in the DOM.
attribute-name.ref="someIdentifier"- Create a reference to a custom attribute's view-model.
view-model.ref="someIdentifier"- Create a reference to a custom element's view-model.
view.ref="someIdentifier"- Create a reference to a custom element's view instance (not an HTML Element).
controller.ref="someIdentifier"- Create a reference to a custom element's controller instance.
<template>
<input type="text" ref="name"> ${name.value}
</template>
String Interpolation
- String Interpolation expressions enable interpolating the result of an expression with text.
- Used in an element's content as an alternative to to-view binding
- Can be used inside attributes, particularly useful in the class and css attributes.
- The interpolated version is much easier to read and easy to remember because the syntax matches the template literal syntax standardized in ES2015/ES6.
- By default, the mode of an interpolation binding is to-view and the result of the expression is always coerced to a string. Results that are null or undefined will result in empty string.
- Used in an element's content as an alternative to to-view binding
- Can be used inside attributes, particularly useful in the class and css attributes.
- The interpolated version is much easier to read and easy to remember because the syntax matches the template literal syntax standardized in ES2015/ES6.
- By default, the mode of an interpolation binding is to-view and the result of the expression is always coerced to a string. Results that are null or undefined will result in empty string.
<template>
<span>${fullName}</span>
<div class="dot ${color} ${isHappy ? 'green' : 'red'}"></div>
</template>
Binding to Select Elements
A typical select element is rendered using a combination of value.bind and repeat. You can also bind to arrays of objects and synchronize based on an id (or similar) property.
Basic Select
<template>
<select value.bind="favoriteColor">
<option>Select A Color</option>
<option repeat.for="color of colors" value.bind="color">${color}</option>
</select>
</template>
Select with Object Array
<template>
<select value.bind="employeeOfTheMonth">
<option>Select An Employee</option>
<option repeat.for="employee of employees" model.bind="employee">${employee.fullName}</option>
</select>
</template>
Select with Object Id Sync
<template>
<select value.bind="employeeOfTheMonthId">
<option>Select An Employee</option>
<option repeat.for="employee of employees" model.bind="employee.id">${employee.fullName}</option>
</select>
</template>
Basic Multi-Select
<template>
<select value.bind="favoriteColors" multiple>
<option repeat.for="color of colors" value.bind="color">${color}</option>
</select>
</template>
Multi-Select with Object Array
<template>
<select value.bind="favoriteEmployees" multiple>
<option repeat.for="employee of employees" model.bind="employee">${employee.fullName}</option>
</select>
</template>
Binding Radios
Basic Radios
<template>
<label repeat.for="color of colors">
<input type="radio" name="clrs" value.bind="color" checked.bind="$parent.favoriteColor" />
${color}
</label>
</template>
Radios with Object Arrays
<template>
<label repeat.for="employee of employees">
<input type="radio" name="emps" model.bind="employee" checked.bind="$parent.employeeOfTheMonth" />
${employee.fullName}
</label>
</template>Radios with a Boolean
<template>
<label><input type="radio" name="tacos" model.bind="null" checked.bind="likesTacos" /> Unanswered</label>
<label><input type="radio" name="tacos" model.bind="true" checked.bind="likesTacos" /> Yes</label>
<label><input type="radio" name="tacos" model.bind="false" checked.bind="likesTacos" /> No</label>
</template>
Binding Checkboxes
- can't use click.delegate on checkboxes if you want to attach a method to it, use change.delegate
Checkboxes with an Array
<template>
<label repeat.for="color of colors">
<input type="checkbox" value.bind="color" checked.bind="$parent.favoriteColors" />
${color}
</label>
<label repeat.for="color of colors">
<input type="checkbox" value.bind="color" checked.bind="$parent.favoriteColors" />
${color}
</label>
</template>
Checkboxes with an Array of Objects
<template>
<label repeat.for="employee of employees">
<input type="checkbox" model.bind="employee" checked.bind= "$parent.favoriteEmployees" />
${employee.fullName}
</label>
</template>
Checkboxes with Booleans
<template>
<li><label><input type="checkbox" checked.bind="wantsFudge" />Fudge</label></li>
<li><label><input type="checkbox" checked.bind="wantsSprinkles" />Sprinkles</label></li>
<li><label><input type="checkbox" checked.bind="wantsCherry" />Cherry</label></li>
<li><label><input type="checkbox" checked.bind="wantsFudge" />Fudge</label></li>
<li><label><input type="checkbox" checked.bind="wantsSprinkles" />Sprinkles</label></li>
<li><label><input type="checkbox" checked.bind="wantsCherry" />Cherry</label></li>
</template>
Binding innerHTML & textContent
Binding innerHTML
<template>
<div innerhtml.bind="htmlProperty | sanitizeHTML"></div>
<div innerhtml="${htmlProperty | sanitizeHTML}"></div>
<div innerhtml="${htmlProperty | sanitizeHTML}"></div>
</template>
- Always use HTML sanitization
- Always use HTML sanitization
- Binding using the innerhtml attribute simply sets the element's innerHTML
property. The markup does not pass through Aurelia's templating system.
Binding expressions and require elements will not be evaluated.
Binding textContent
<template>
<div textcontent.bind="stringProperty"></div>
<div textcontent="${stringProperty}"></div>
<div textcontent.bind="stringProperty"></div>
<div textcontent="${stringProperty}"></div>
</template>
Two-Way Editable textContent
<template>
<div textcontent.bind="stringProperty" contenteditable="true"></div>
</template>
<div textcontent.bind="stringProperty" contenteditable="true"></div>
</template>
Declaring Computed Property Dependencies
import {computedFrom} from 'aurelia-framework';
export class Person {
firstName = 'Pradnya';
lastName = 'Kulkarni';
@computedFrom('firstName', 'lastName')
get fullName(){
return `${this.firstName} ${this.lastName}`;
}
}
Comments
Post a Comment