如何从敲除绑定获取 DOM 元素? [英] How to get to the DOM element from a knockout binding?

查看:22
本文介绍了如何从敲除绑定获取 DOM 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用淘汰赛将 DOM 元素绑定到 viewModel.当我更改底层模型的属性时,它会更改 DOM - 一切正常.

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.

但是,有没有办法访问绑定的 DOM 元素,以便在底层模型从外部更新时向其添加一个类?

However, is there a way to get to the bound DOM element so I can add a class to it when the underlying model gets updated externally?

我使用了自定义绑定,它让我可以访问 DOM 元素,但我想知道是否有更简单的方法直接从 viewModel 的绑定属性?

I have used custom binding which gives me access to the DOM element but I was wondering if there is a simpler way directly from the viewModel's bound property?

谢谢

示例代码(打字稿)

SetMyCell(row: number, newValue: any) {

    var ditem = this._DataItems[row];

    // update the actual value    
    ditem.Producer(newValue);

    // Now I wish to decorate the DOM item this Producer property is 
    // bound to with a class. How to go about that?

}

推荐答案

例如,您可以滥用可见绑定来执行传递 $element 和 $data 的函数.

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

<span data-bind="visible: func1($element, $data)">Test span</span>

看看这个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");
    };
    ......
};

和 html 将是

<button data-bind="click: btnClick">change element text or something else</button>
<span data-bind="widget: spanElement"></span>

我已经更新了fiddle所以你可以看到它的实际效果

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

这篇关于如何从敲除绑定获取 DOM 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆