使用Jquery更改值时KnockoutJS属性不会更新 [英] KnockoutJS property doesn't update when changing value with Jquery

查看:101
本文介绍了使用Jquery更改值时KnockoutJS属性不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的复选框,我想收集所选的复选框.复选框位于div中,单击div时也应选中该复选框:

I have a serie of checkboxes and I want to gather the selected one. The checkboxes are in div's and when the div is clicked the checkbox should get checked as well:

var oCheckBox = $($(this).find('.chkSocialMediaItem').get(0));
oCheckBox.attr('checked', !$(oCheckBox).attr('checked'));

这很好用,但KnockoutJS不会接受更改,因此不会更新所选项目的计数器.

This works just fine but KnockoutJS doesn't pick up the change and so doesn't update my counter on the selected items.

我在某个地方读到需要触发变更事件的地方.但是,当我在复选框上监听更改事件时,它实际上确实会被触发.

I read somewhere you need to trigger the change event. But when I listen to the change event on the checkbox it does actually get triggered.

任何帮助,我们将不胜感激, 谢谢!

Any help would be appreciated, Thanks !

更新:

我找到了一种淘汰赛"解决方案. 在我的div中,我对"click"进行了数据绑定,并更改了该函数中的检查值:

I have found a 'knockout' solution. In my div I did a data-bind off the 'click' and changed the checked value in that function:

<script type="text/html" id="Template">
    <div class="item" data-bind="click: DivClicked">
       <input type="checkbox" data-bind="checked: IsASelectedItem" class="chkSocialMediaItem"/>
    </div>
</script>


function SocialMediaSearchItem() {          
            this.IsASelectedItem = ko.observable();
            this.DivClicked = function () {
                this.IsASelectedItem(!this.IsASelectedItem());
            };
}

这是唯一的解决方案吗?我真的很想2也看到一个Jquery解决方案.

Is this the only solution? I would really like 2 see a Jquery solution as well.

推荐答案

checked绑定仅侦听click事件.手动触发click事件最终会导致框基于设置实际检查值的时间不同步.

The checked binding only listens to the click event. Manually triggering the click event ends up getting the box out-of-sync based on when the actual checked value is set.

设置值的首选方法是更新视图模型值,就像在上面的第二个示例中所做的那样.

The preferred way to set the value is to update your view model value, as you have done in your second example above.

但是,如果您使用的是 1.3beta ,那么就有一种简单的方法可以使用ko.dataFor API将元素与其相应的数据连接起来.看起来像这样:

However, if you are using 1.3beta, then there is an easy way to connect an element with its corresponding data using the ko.dataFor API. It would look something like:

  var oCheckBox = $('.chkSocialMediaItem'),
      data = ko.dataFor(oCheckBox[0]);
      data.selectedItem(!data.selectedItem());

这篇关于使用Jquery更改值时KnockoutJS属性不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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