简体   繁体   English

将对象从数组推送到observableArray

[英]push object from an array to observableArray

so I'm trying to push the object stored in an array when a checkbox is called with knockout to an observable array. 因此,当使用带挖空功能的复选框调用时,我试图将存储在数组中的对象推送到可观察数组。

HTML: HTML:

<input type="checkbox" data-bind="checked: checked, click: $root.saveSelected"/>

JS: JS:

var definition = [
      {title: 'some text', checked: ko.observable(false), definition: '<p>Some HTML</p>'}
],

var viewModel = {

selectedItems: ko.observableArray([]),

saveSelected: function() {
      for (var i = 0; i < definition.length; ++i) {
        if (viewModel.definition[i].checked().value === true) {
          viewModel.selectedItems.push(definition[i]);
        }
      }
    }

So I'm pretty sure that my if statement is what's causing the issue here, but I'm not sure what I did wrong. 因此,我很确定我的if语句是导致此问题的原因,但我不确定自己做错了什么。 But the outcome should be that for every checkbox that is selected, that object (now with a value of true for 'checked') should get pushed to the selectedItems array so that (with this example) the blank selectedItems array should have the object 但是结果应该是,对于每个选中的复选框,该对象(现在“ checked”的值为true)应该被推送到selectedItems数组,以便(在本示例中)空白的selectedItems数组应该具有该对象

{title: 'some text', checked: ko.observable(false), definition: '<p>Some HTML</p>'} 

in it after the saveSelection function runs. 在其中运行saveSelection函数之后。

--EDIT-- The fiddle for this code: http://jsfiddle.net/imagitron/mMc6k/6/ -编辑-此代码的小提琴: http : //jsfiddle.net/imagitron/mMc6k/6/

Remove the ".value" when accessing the checked observable: 访问选中的可观察对象时,请删除“ .value”:

if (viewModel.definition[i].checked() === true) {
...

Knockout manages setting the value of the HTML <input> control. 敲除管理设定value的HTML <input>控制。 All you need to know is that it's an observable with either true or false value. 您只需要知道它是可观察的,则可以是truefalse值。

First off, click: $root.saveSelected doesn't match saveSelection: function() { 首先, click: $root.saveSelectedsaveSelection: function() {不匹配saveSelection: function() {

Second issue 第二期

for (var i = 0; i < definition.length; ++i) {
    if (viewModel.definition[i].checked() === true) {

definition and viewModel.definition are two seperate things here. 定义和viewModel.definition是这里的两个分开的东西。 viewModel.definition is actually with the first save an empty array. viewModel.definition实际上是先保存一个空数组。 so, viewModel.definition[i] won't work ... 因此,viewModel.definition [i]无法正常工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM