Friday, December 18, 2015

Aurelia - binding and custom elements

One more thing that seems to bite me with custom elements. By default, attributes of custom elements are one-way bound. That means, if I do

    <my-element attribute.bind="somethingFromMyViewModel"></my-element>

Then if the custom element changes the value of attribute, that change will not be reflected in somethingFromMyViewModel. The simple fix is to do:

    <my-element attribute.bind="somethingFromMyViewModel"></my-element>

That has the downside of having to remember it every time. If you have a view model, then you can change the default for a binding. To simply change this one binding to two way, you need only do add:
import {bindable, bindingMode} from 'aurelia-framework';

@bindable ({
  name: 'attribute',
  defaultBindingMode: bindingMode.twoWay
export class MyElementCustomElement {

Unfortunately, right now you have to have a view model to change the default binding. If you have an HTML-only component, you are stuck.

1 comment:

William Hayes said...

You can use attribute.two-way to create a two-way binding mode from where you use the custom element. This of course depends on the user of the custom element to use the right binding mode.