How to get to the DOM element from a knockout binding?

后端 未结 1 554
故里飘歌
故里飘歌 2021-01-17 18:56

I have bound a DOM element to a viewModel using knockout. When I change a property on the underlying model it changes the DOM - all ok.

However, is there a way to ge

1条回答
  •  -上瘾入骨i
    2021-01-17 19:41

    You can abuse the visible binding for example to execute a function passing the $element and $data.

    Test span
    

    look at this fiddle

    I know you mention above that you don't want to use a custom binding but i still want to point out this option. although i am using a custom binding the logic for modifying the element will still happen in the viewmodel when the external changes happen.

    ko.bindingHandlers.widget = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var elemObservable = valueAccessor();
            if (ko.isObservable(elemObservable)) {
                elemObservable(element);
            }
        }
    };
    
    var vm = function () {
        var self = this;
        .....
        self.spanElement = ko.observable();
        self.btnClick = function (){
            var elem = self.spanElement();
            $(elem).html("This is the span element");
        };
        ......
    };
    

    and the html would be

    
    
    

    I have updated the fiddle so you can see it in action

    0 讨论(0)
提交回复
热议问题