简体   繁体   中英

Knockout computed vs custom binding calculation order

I defined a custom binding that alters some way an observable's property, let's say customProperty. (for example):

ko.bindingHandlers.customBinding = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //computes some value depending on observable value
        //...
        valueAccessor().customProperty = someValue;
    }
};

I also have a computed observable that triggers on my customBinded observable, in which I need the value of customProperty updated. It turns out logging inside custom binding and in computed code that computed is calculated before customBinding, so it reads old customProperty value.

Can I specify that binding has priority over computeds, or is there some workaround to achieve computed to "wait" for custom binding?

You can use the Rate-limiting observable notifications to delay the execution of the computed observable. eg

viewModel.computed = ko.computed(function() {
  var input = viewModel.input();
  return viewModel.input.customProperty + ' ' + input;
}).extend({rateLimit: 10 });

The slight delay will allow the binding to execute before the computed observable. See this JSFiddle example for a demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM