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

后端 未结 2 1765
猫巷女王i
猫巷女王i 2021-01-27 00:11

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


                        
    
提交评论

  • 2021-01-27 00:57

    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)
    
        }
    }
    
    0 讨论(0)
  • 提交回复
    热议问题