Pregunta

I've built a system where I've got a user interface, each modification has to send an Ajax request to the server (where business logic is applied) and a new set of values for the UI are sent back. This process doesn't lock the UI so you can 'chain' changes and have multiple Ajax requests going on at once.

I'm using knockout and obviously wanted to prevent a recursive update going on here, so what I did is this:

  • Apply custom subscribers to each observable item.
  • When an observable changes, an Ajax setFeatures request is made.
  • Once the Ajax setFeatures request completes, an Ajax getFeatures takes place and data is returned to a callback only if there are no additional ajax requests running
  • The callback sets a flag which prevents additional Ajax setFeatures being made.
  • Knockout observables are set at this point no more Ajax requests should be sent
  • The flag is reverted to allow Ajax requests to be sent again.

What I've noticed is that the first time this cycle takes place (setFeatures, getFeatures) each knockout observable triggers another setFeatures (this stops here and doesn't recurse).

Any point after this initial run it behaves as expected. It's quite difficult to share the large amount of code but I believe the reason for this is may be due to the following:

  skipUpdate = true;

 // Update each of the knockout fields
 $(data).each(function () {
    var block = viewModel[this.Block];
    var item = block[this.Name]
    item.control.value(this.Value);    // item.control.value is the observable
 });

 skipUpdate = false;

Due to JavaScript being single threaded, would I be correct in assuming that the knockout observables are updated after this block of code is executed? Or should they be updated within the skipUpdate flags?

¿Fue útil?

Solución

Normally, an observable that is changed notifies its subscribers immediately, so that any computed observables or bindings that depend on the observable are updated synchronously.

To avoid such update and make update asynchronously you can use rate-limiting observable notifications which is new feature of knockoutJS 3.1, before that there was thing, called throttle extender.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top