Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatical changes will not reflect in knockout viewmodel

To change the status of a checkbox with javascript doesn't correspond to the spirit of MVVM. But I'm creating a general javascript library for better looking standard controls like checkbox, radio button or selectbox. Based on the following viewmodel:

function MyViewModel() {
  var self = this;

  self.ok = ko.observable();

};

var vm = new MyViewModel();
ko.applyBindings(vm);

But I get a problem in conjunction with knockout when I change the checked status of a checkbox programmatically:

document.getElementById('chk').checked = true

The change will not appear in the property of the viewmodel. But when I click the checkbox all works fine.

Look at http://jsfiddle.net/KWdZB/1/

Is there any workaround?

like image 405
Ralf Avatar asked Apr 23 '26 13:04

Ralf


1 Answers

Your problem is that ko subscribes on the click event inside the checked binding:

ko.utils.registerEventHandler(element, "click", updateHandler);

But changing the checked attribute won't trigger the click event so ko won't be notified.

If you manually trigger the click event after the attribute change it can work...

I don't know how to do it with pure javascript but with jQuery you can write:

$('#chk').attr('checked', true).triggerHandler('click')

You can test it in this JSFiddle.

like image 168
nemesv Avatar answered Apr 26 '26 10:04

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!