Get element an observable is bound to with Knockout?

后端 未结 2 1405
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 22:33

This isn\'t an ideal situation, but due to another knockout binding I am using I am in a situation where I am needing to get the element an observable is bound to, if it is

相关标签:
2条回答
  • 2020-12-15 23:36

    I have done something similar to what you mentioned above. My data-bind tag includes a custom binding:

    data-bind="... myvalidationbinding: myobservable"
    

    Then in my binding handler I extend the observable

    ko.bindingHandlers.myvalidationbinding = {
      init: function (element, valueAccessor, allBindingsAccessor, viewModel) { 
        valueAccessor().extend({element: element });
      }
    };
    

    And finally my extension is

    ko.extenders.element = function (target, element) {
      target.DOMElement = element;
    }
    

    Now I can subscribe to isValid() given by knockout.validation and if not valid, go get the element the observable is bound to and then manipulate it with jQuery.

    0 讨论(0)
  • 2020-12-15 23:37

    This won't be very fast, so I would definitely cache the results, but something using jQuery's attribute selectors:

    $('[data-bind*="Property"]')
    

    *= is the attribute contains selector: http://api.jquery.com/attribute-contains-selector/

    Obviously this won't catch anything that subscribed manually using the .subscribe method, but I'm not sure how you would extract element's from the functions anyway.

    Disclaimer: while this solution will probably work, this sounds like a horrible idea to me, I would instead write a custom binding (as mentioned in the comments) or find some other solution.

    0 讨论(0)
提交回复
热议问题