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

查看:51
本文介绍了如何从敲除绑定中获取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的bind属性中找到一种更简单的方法?

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?

谢谢

示例代码(TypeScript)

sample code (TypeScript)

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>

看看这个小提琴

我知道您在上面提到您不想使用自定义绑定,但是我仍然想指出此选项.尽管我使用的是自定义绑定,但是当发生外部更改时,用于修改元素的逻辑仍然会在视图模型中发生.

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>

我已经更新了小提琴,因此您可以在操作中看到它

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

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

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