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

风流意气都作罢 提交于 2019-12-02 10:57:40

问题


I need to get data bind keys and value observable using element.

<select id="selector" data-bind="options:selectOptions,value:selectedValue"></select>

var ViewModel = {
   selectOptions:ko.observableArray([...]),
   selectedValue:ko.observable()
   ...
   some other stuff
   ...
}

In other viewmodel I can access dom element now I need to update element's binding context observable.

how can I get data-bind keys and values?

I need something like this

{
   options:selectOptions,
   value:selectedValue
}

回答1:


ko.dataFor(element) will help. See -

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

In your other view-model where you have the element, call:

var bound_vm = ko.dataFor(element)

bound_vm will then be whatever view-model was bound against that element.

I don't think you can get the key/vals of the original binding; KO has parsed it into functions. Presumably in your other view-model you want to change whatever is bound to options, but you don't know what it is called? You could do something like this with jQuery to parse the original data-bind attribute:

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)

    }
}



回答2:


Well i recommend you use this. You can handle it on javascript end using jquery unobtrusive plugin.

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

For this you can create an object

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

And use it like this

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

Instead of this

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

this way you will have the binding object available to reuse and your code will be quite clean. Make sure you call it before applyBinding.



来源:https://stackoverflow.com/questions/25116043/knockout-how-to-get-data-bind-keys-and-value-observables-using-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!