程序更改不会反映在剔除视图模型中 [英] Programmatical changes will not reflect in knockout viewmodel

查看:64
本文介绍了程序更改不会反映在剔除视图模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript更改复选框的状态与MVVM的精神不符.但是我正在创建一个通用的javascript库,以使外观更好的标准控件(如复选框,单选按钮或选择框). 基于以下视图模型:

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

更改将不会出现在viewmodel的属性中.但是当我单击复选框时,一切正常.

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

查看 http://jsfiddle.net/KWdZB/1/

有什么解决方法吗?

推荐答案

您的问题是ko订阅了

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

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

但是更改checked属性不会触发click事件,因此不会通知ko.

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

如果您在属性更改后手动触发click事件,则它可以正常工作...

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

我不知道如何使用纯JavaScript来做到这一点,但是使用jQuery,您可以编写:

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

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

您可以在此 JSFiddle 中对其进行测试.

You can test it in this JSFiddle.

这篇关于程序更改不会反映在剔除视图模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆