Aurelia bindable and jQuery plugins

Asked

Viewed 26 times

0

I have a problem with bindable variables and jQuery plugins that manipulate input value. I tested the following code and found that Aurelia does not listen to the changes of values made by $.fn.val:

<template>
  <input id="my-input" value.bind="inputvalue" type="text">
</template>

class MyClass {
  @bindable inputvalue;

  constructor() {
    this.inputvalue = 'First value'
  }

  bind() {
    setTimeout(() => {
      $('#my-input').val('Some value').change();
      // No input o valor é 'Some value',
      // mas na variável bindable this.inputvalue o valor ainda é 'First value'
    }, 4000);
  }
}

Is there any way to solve this problem?

1 answer

1

First, the ideal:

Like the Binding is connecting Aurelia objects (ie View and Viewmodel), ideally you would not use an external agent (jQuery in this case) to update your View directly. This will cause the change not to be tracked and, consequently, the aforementioned desynchronization occurs.

Solution:

bind() {
  setTimeout(() => {
    // setar o valor diretamente em sua VM, que então atualizará a View, 
    // considerando que o bind padrão para inputs é de duas vias (two-way)
    this.inputvalue = 'Some value';     
  }, 4000);
}

Now, the workaround:

If the situation is actually more complex and you really have to force Binding refresh manually, you need to signal this action.

For that reason:

1) In its View, add Binding behavior of type signal the desired Binding(s) (s)):

<template>
  <input id="my-input" value.bind="inputvalue & signal:'forcar-refresh'" type="text">
</template>

2) In its Viewmodel, flag the change by notifying all registered bindings to update themselves:

import {BindingSignaler} from 'aurelia-templating-resources';

@inject(BindingSignaler)
class MyClass {
  @bindable inputvalue;
  signaler;

  constructor(signaler) {
    this.inputvalue = 'First value';
    this.signaler = signaler;
  }

  bind() {
    setTimeout(() => {
      $('#my-input').val('Some value').change();
      this.signaler.signal('forcar-refresh'); // <--- Aqui
    }, 4000);
  }
}
  • I managed to solve the problem, I think using the value.two-way if I’m not mistaken. That answer on the Soen helped me. But when I have a little time I’ll test your answer.

  • Legal @Kaduamaral. If you can retrieve your solution and verify that it is easier to implement, I believe it would be worth posting it here and mark as the answer.

  • Yes I will when I have a little time... Thanks for the answer. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.