如何将对象推送到observableArray

时间:2015-11-04 09:44:03

标签: javascript knockout.js

我有这个模型,Foo有很多FooItem。如何将对象添加到FooItem

我有这段代码,你可以建议甚至删除最适合这种情况的整个代码

var Foo = function (selected) {
    this.id = ko.observable();
    this.name = ko.observable();
    this.fooItems = ko.observableArray([]);
    this.isSelected = ko.computed(function() {
        return selected() === this;
    }, this);
};

var FooItem = function () {
    this.id = ko.observable();
    this.selectedItemId = ko.observable();
    this.selectedName = ko.observable();
    this.remarks = ko.observable();
};

var foosFromDb = [{ id: 1, name: 'foo1' },
    { id: 2, name: 'foo2' },
    { id: 3, name: 'foo3' },
    { id: 4, name: 'foo4' }];

var fooItemsFromDb = [
    { id: 1, fooItem: 'fooItem1' },
    { id: 2, fooItem: 'fooItem2' },
    { id: 3, fooItem: 'fooItem3' },
    { id: 4, fooItem: 'fooItem4' },
    { id: 5, fooItem: 'fooItem5' },
    ];

var vm = (function () {
    var 
    	foos = ko.observableArray([]),
        fooItemsList = ko.observableArray([]),
    	loadFoos = function() {
            for(var i = 0; i < foosFromDb.length; i++) {
                foos.push(new Foo(selectedFoo)
                          .id(foosFromDb[i].id)
                          .name(foosFromDb[i].name));
            }
            
            selectFoo(foos()[0]);
        },
        loadFooItemsList = function() {
            for(var i = 0; i < fooItemsFromDb.length; i++) {
                fooItemsList.push({ id: fooItemsFromDb[i].id, name: fooItemsFromDb[i].fooItem });
            }
        },
        selectedFoo = ko.observable(),
        selectFoo = function(item) {
            selectedFoo(item);
        },
        newFoo =  function(item) {
           var id = foos().length + 1;
           var aFoo = new Foo(selectedFoo)
           				.id(id)
           				.name('');
            
            foos.push(aFoo);
            selectFoo(aFoo);
        },
        addFooItem = function(item){
            console.log(item); // In here I think I am getting the Selected Foo.
        };
    
    return {
        foos: foos,
        loadFoos: loadFoos,
        newFoo: newFoo,
        selectedFoo: selectedFoo,
        selectFoo: selectFoo,
        loadFooItemsList: loadFooItemsList,
        fooItemsList: fooItemsList,
        addFooItem: addFooItem
    };
}());

vm.loadFoos();
vm.loadFooItemsList();
ko.applyBindings(vm);
.container {
    float: left;
    width: 200px;
    height: 250px;
    border: 1px solid #ccc;
}
.selected  {
    background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="container">
    <a href="#" data-bind="click: newFoo">New Foo</a>
    <table>
        <tr>
            <th>Foo Id</th>
            <th>Foo Name</th>
        </tr>
        <tbody data-bind="foreach: foos" style="cursor: pointer">
            <tr data-bind="click: $root.selectFoo, css: { selected: isSelected }">
                <td data-bind="text: id"></td>
                <td data-bind="text: name"></td>
            </tr>
        </tbody>
    </table>
</div>
<div data-bind="with: selectedFoo">
    <div class="container">
        <label>Id</label><br /><input type="text" data-bind="value: id" /><br />
        <label>Name</label><br /><input type="text" data-bind="value: name" /><br />
    </div>
    <div class="container">
        <label>Foo Item</label><br /><select data-bind="options: $root.fooItemsList, 
                                                        optionsText: 'name', 
                                                        optionsValue: 'id'"></select><br />
        <label>Remarks</label><br /><input type="text" /><br />
        <a href="#" data-bind="click: $root.addFooItem">Add Foo Item</a>
    </div>
        <div class="container">
        <table>
            <thead>
                <tr>
                    <th>FooItem</th>
                    <th>Remarks</th>
                </tr>
            </thead>
        </table>
    </div>
</div>
<div style="clear: both"></div>
<pre data-bind="text: ko.toJSON($root.selectedFoo, null, 2)"></pre>

当我click 添加Foo项时,我希望填充在字段中输入的表格(在最右边)并填充{{1 fooItems的属性。

我有fiddle作为参考

欢迎提出建议,提示或任何编码实践。任何帮助将非常感激。感谢

修改 我最终发布了整个视图模型。哪个错了

1 个答案:

答案 0 :(得分:1)

你缺少一些必要的东西来连接所有东西。你的select没有绑定任何东西,你没有一个可观察到它的绑定。我为selectedItem添加了Foo成员。

我选择的项目optionsValue已被选中,因为我不想查找它。值不是FooItem,而是具有id和name的简单对象。在addFooItem中,我从对象数据中创建一个新的FooItem并将其推送到fooItems列表。

桌子主体没有定义,所以我把它设置为显示。出于某种原因,保存备注会导致以前保存的所有备注都更新。我不知道为什么会这样,但我发现整个结构有点难以理解。

&#13;
&#13;
var Foo = function(selected) {
  this.id = ko.observable();
  this.name = ko.observable();
  this.fooItems = ko.observableArray([]);
  this.isSelected = ko.computed(function() {
    return selected() === this;
  }, this);
  this.selectedItem = ko.observable('quack');
};

var FooItem = function() {
  this.id = ko.observable();
  this.selectedItemId = ko.observable();
  this.selectedName = ko.observable();
  this.remarks = ko.observable();
};

var foosFromDb = [{
  id: 1,
  name: 'foo1'
}, {
  id: 2,
  name: 'foo2'
}, {
  id: 3,
  name: 'foo3'
}, {
  id: 4,
  name: 'foo4'
}];

var fooItemsFromDb = [{
  id: 1,
  fooItem: 'fooItem1'
}, {
  id: 2,
  fooItem: 'fooItem2'
}, {
  id: 3,
  fooItem: 'fooItem3'
}, {
  id: 4,
  fooItem: 'fooItem4'
}, {
  id: 5,
  fooItem: 'fooItem5'
}, ];

var vm = (function() {
  var
    foos = ko.observableArray([]),
    fooItemsList = ko.observableArray([]),
    loadFoos = function() {
      for (var i = 0; i < foosFromDb.length; i++) {
        foos.push(new Foo(selectedFoo)
          .id(foosFromDb[i].id)
          .name(foosFromDb[i].name));
      }

      selectFoo(foos()[0]);
    },
    loadFooItemsList = function() {
      for (var i = 0; i < fooItemsFromDb.length; i++) {
        fooItemsList.push({
          id: fooItemsFromDb[i].id,
          name: fooItemsFromDb[i].fooItem
        });
      }
    },
    selectedFoo = ko.observable(),
    selectFoo = function(item) {
      selectedFoo(item);
    },
    newFoo = function(item) {
      var id = foos().length + 1;
      var aFoo = new Foo(selectedFoo)
        .id(id)
        .name('');

      foos.push(aFoo);
      selectFoo(aFoo);
    },
    addFooItem = function(foo) {
      var itemData = foo.selectedItem(),
          item = new FooItem();
      item.id(itemData.id);
      item.selectedName(itemData.name);
      var r = vm.remark();
      console.debug("Remark:", r);
      item.remarks(r);
      foo.fooItems.push(item);
    };

  return {
    foos: foos,
    loadFoos: loadFoos,
    newFoo: newFoo,
    selectedFoo: selectedFoo,
    selectFoo: selectFoo,
    loadFooItemsList: loadFooItemsList,
    fooItemsList: fooItemsList,
    remark: ko.observable(),
    addFooItem: addFooItem
  };
}());

vm.loadFoos();
vm.loadFooItemsList();
ko.applyBindings(vm);
&#13;
.container {
  float: left;
  width: 200px;
  height: 250px;
  border: 1px solid #ccc;
}
.selected {
  background-color: red;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="container">
  <a href="#" data-bind="click: newFoo">New Foo</a>
  <table>
    <tr>
      <th>Foo Id</th>
      <th>Foo Name</th>
    </tr>
    <tbody data-bind="foreach: foos" style="cursor: pointer">
      <tr data-bind="click: $root.selectFoo, css: { selected: isSelected }">
        <td data-bind="text: id"></td>
        <td data-bind="text: name"></td>
      </tr>
    </tbody>
  </table>
</div>
<div data-bind="with: selectedFoo">
  <div class="container">
    <label>Id</label>
    <br />
    <input type="text" data-bind="value: id" />
    <br />
    <label>Name</label>
    <br />
    <input type="text" data-bind="value: name" />
    <br />
  </div>
  <div class="container">
    <label>Foo Item</label>
    <br />
    <select data-bind="options: $root.fooItemsList, 
                       optionsText: 'name', 
                       value: selectedItem"></select>
    <br />
    <label>Remarks</label>
    <br />
    <input type="text" data-bind="value: $root.remark" />
    <br />
    <a href="#" data-bind="click: $root.addFooItem">Add Foo Item</a>
  </div>
  <div class="container">
    <table>
      <thead>
        <tr>
          <th>FooItem</th>
          <th>Remarks</th>
        </tr>
      </thead>
      <tbody data-bind="foreach: fooItems">
        <td data-bind="text:selectedName"></td>
        <td data-bind="text:$root.remark"></td>
        </tbody>
    </table>
  </div>
</div>
<div style="clear: both"></div>
<pre data-bind="text: ko.toJSON($root.selectedFoo, null, 2)"></pre>
&#13;
&#13;
&#13;