Initialize Knockout observable from element attribute value

前端 未结 2 655
不思量自难忘°
不思量自难忘° 2021-02-05 14:30

I have an element that possesses an attribute whose value is bound to a knockout observable:

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 15:10

    Another option would be to use a custom binding, and collect the current value of the element in the init function. This is much more reusable, in my opinion.

    ko.bindingHandlers.transform = {
        init: function(element, valueAccessor) {
            valueAccessor()(element.getAttribute('transform'));
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            element.setAttribute('transform', ko.utils.unwrapObservable(value))
        }
    };
    

    Of course, yours will be more complicated, since you must be doing something with this transform property. That logic will probably want to go in the update section.

提交回复
热议问题