I want to determine why Knockout.js custom binding called update

Asked 1 years ago, Updated 1 years ago, 70 views

Creating custom bindings for Knockout.js.

For example, data-bind="MyBind:{value:vmCode,size:vmLength}", if the MyBind custom binding update method was called by a change in value(vmCode), or by size(vmCode).

Is there any way to do that?

javascript knockout.js

2022-09-30 11:35

1 Answers

Simply remember the previous value somewhere and you can compare it.

ko.bindingHandlers.MyBind={  
    update:function(element, valueAccessor){

        // Obtain the current value of the binding
        varobj=ko.unwrap(valueAccessor());
        value = ko.unwrap(obj.value);
        var size = ko.unwrap(obj.size);

        // retrieve the previously saved value
        varp=element.__MyBindPreviousValue;

        // TODO: Process with current and previous values
        element.innerText=`${value},${size}<=(${p?p.value:'},${p?p.size:'}')`;

        // save this time's value in the right place
        // Here we simply set the value for element.
        element.__MyBindPreviousValue={value:value,size:size};
    } 
};

For Observable, you can also register listeners like obj.value.subscribe(function(){}).This is sufficient if you want to do a little work within the VM, but if you have a question, it will be complicated if you explicitly manage it with subscribe because it is a composite object to be monitored.


2022-09-30 11:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.