Aurelia how to make an optional binding

Does Aureliaoptional binding support ? I can not find this information anywhere. The problem I am facing is that I have an attribute titlethat may or may not be populated in an array of objects. I use repeat.forand title.bind, but I do not want the attribute to exist at all if this property is not part of an array of objects. Is this possible in Aurelia?

When used Bootstrap-Selectwith an empty one, titleit throws an error. If you Aureliacreate the attribute on the fly, this will solve my problem.

The code I still have is as follows:

<select class="selectpicker" value.bind="value" options.bind="options" disabled.bind="disabled">
<option repeat.for="option of options" model.bind="option"
        data-subtext.bind="option.subtext"
        title.bind="option.title">
        ${option.name}
</option>

In this example, I wanted to do data-subtext, and titleadditional attributes. Is this doable?

Since this is a user element, I tried to remove the property of titlemy object delete this.element.title, but this does not work. I also tried with jquery but again no luck.

+2
source share
2 answers

I have not tested this in many cases, but I think you can also create custom binding behavior, for example:

export class OptionalBindingBehavior {  
  bind(binding, scope, interceptor) {

    binding.originalupdateTarget = binding.updateTarget;
    binding.originalTargetProperty = binding.targetProperty;
    binding.updateTarget = val => { 
      if (val === undefined || val === null || val === '') {
        binding.targetProperty = null;
      } else {
        binding.targetProperty = binding.originalTargetProperty;
      }
      binding.originalupdateTarget(val);   
    }
  }

  unbind(binding, scope) {
    binding.updateTarget = binding.originalupdateTarget;
    binding.originalupdateTarget = null;    
    binding.targetProperty = binding.originalTargetProperty;
    binding.originalTargetProperty = null;
  }
}

And then use it like:

<a href.bind="message & optional">${message}</a>
+3
source

You can use a custom attribute that generates an attribute titleonly if the property exists. For example:

export class OptionalTitleCustomAttribute {

  static inject = [Element];

  constructor(element) {
    this.element = element;
  }

  valueChanged(newValue) {
    if (newValue) {
      this.element.setAttribute('title', newValue);
    } else {
      this.element.removeAttribute('title');
    }
  }

}

Execution example: https://gist.run/?id=f7f89f35b62acb5b4f05ffe59be1880e

+2
source

Source: https://habr.com/ru/post/1016027/


All Articles