了解如何使用element获取数据绑定键和值可观察对象

Knockout how to get data-bind keys and value observables using element?

本文关键字:键和值 观察 对象 数据绑定 获取 何使用 element 了解      更新时间:2023-09-26

我需要使用element获取数据绑定键和值观察。

<select id="selector" data-bind="options:selectOptions,value:selectedValue"></select>
var ViewModel = {
   selectOptions:ko.observableArray([...]),
   selectedValue:ko.observable()
   ...
   some other stuff
   ...
}

在其他视图模型中,我可以访问dom元素,现在我需要更新元素的绑定上下文可观察对象。

如何获得数据绑定键和值?

我需要这样的东西

{
   options:selectOptions,
   value:selectedValue
}

ko.dataFor(element)将有所帮助。看到——

http://knockoutjs.com/documentation/unobtrusive-event-handling.html

在其他视图模型中,调用:

var bound_vm = ko.dataFor(element)

bound_vm将是绑定到该元素的视图模型。

我不认为你可以得到原始绑定的键/值;KO将其解析为函数。假设在您的其他视图模型中,您希望更改绑定到选项的任何内容,但您不知道它被称为什么?您可以使用jQuery做这样的事情来解析原始的data-bind属性:

OtherViewModel: {
    the_logic: function() {
        // We have the element already
        var element = [already set to a DOM node]
        // Get the view-model bound to the element
        var bound_vm = ko.dataFor(element)
        // Parse the original binding attribute on the element
        $($(element).attr("data-bind").split(",")).each(
            function(idx, binding) {
                var parts = binding.split(":")
                binding_info[parts[0].trim()] = parts[1].trim()
            }
        )
        // Now binding_info should hold what you want. EG we can set whatever
        // the options binding is bound to like this:
        bound_vm[binding_info[options]]([1,2,3)
    }
}

我建议你使用这个。你可以在javascript端使用jquery unobtrusive plugin来处理它。

http://joel.net/unobtrusive-data-binding-for-knockout-js

你可以创建一个对象

var binding = {
    options: 'tickets',
    optionsCaption: "'Choose...'",
    optionsText: "'name'",
    value: 'chosenTicket'
}

像这样使用

$('#tickets').dataBind(binding);

而不是

<select 
    data-bind="
        options: tickets, 
        optionsCaption: 'Choose...',
        optionsText: 'name',
        value: chosenTicket
    "
></select>

这样,您将拥有可重用的binding对象,并且您的代码将非常干净。确保在applyBinding之前调用