Skip to content Skip to sidebar Skip to footer

Not Able To Trigger Knockout Data-bind Using Jquery

I am writing a plugin using jQuery and knockout. I have two radio buttons. I am using knockout data-bind to check and uncheck the radio button. The problem is that when I am trying

Solution 1:

jQuery and Knockout are fighting over control of the view. If you're going to use a viewmodel, use the viewmodel and do not manipulate the DOM except through the viewmodel. You have a viewmodel element that controls the radio buttons, you just need to set it. Knockout provides a click binding, so you don't need jQuery to attach that, either.

varViewModel = function () {
    var self = this;
    self.selectedVal = ko.observable("fixedPrice");
    self.selectedVal.subscribe(function (val) {
        console.log(val)
    });
    self.setSelected = function () {
        self.selectedVal('allowBiding');
    };
};

ko.applyBindings(newViewModel());
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><inputtype="radio"data-bind="checked: selectedVal"name="1"value="fixedPrice" />Fixed Price
<inputtype="radio"data-bind="checked: selectedVal"name="1"value="allowBiding" />Allow Biding
<predata-bind="text:ko.toJSON($data,null,2)"></pre><inputtype="button"value="Click Me"data-bind="click:setSelected" />

Solution 2:

Welp! Don't mix KO and jQuery in this way. You're fighting Knockout, not using it. See this earlier answer I wrote for a very similar situation and extended explanation.

Note that this is certainly not a bug, jQuery will by default not trigger events on DOM changes like that. If you insist on mixing KO and jQuery this way, be sure to notify others like this:

ko.applyBindings({
  isChecked: ko.observable(false),  
  onClick: function() {
    $('.hn').prop('checked', true);
    $('.hn').trigger('click');
  }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1. The radio button: <inputtype="radio"class="hn"data-bind="checked: isChecked"><br>
2. Trigger it with jQuery: <buttondata-bind="click: onClick">trigger</button><hr>
Debug info:<br><textareadata-bind="text: ko.toJSON($root)"></textarea>

Solution 3:

It looks like a bug. However, you can try to invoke the native click handler so the observable will be updated.

$('.hn').triggerHandler('click');

Or

$('.hn')[0].click();

Here is a JsFiddle Demo

Post a Comment for "Not Able To Trigger Knockout Data-bind Using Jquery"