我怎样才能创建一个基因敲除的观察值数组? [英] How to can I create an array of knockout.js observables?

查看:74
本文介绍了我怎样才能创建一个基因敲除的观察值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我正在为其显示其属性. 如何为他们添加单独的编辑功能?可以说它是列表中每个元素的编辑按钮.

I have an array of objects for which I am showing their properties. How can add an individual edit functionality to them? Lets say it to be an edit button for each one of the elements of the list.

当对象处于编辑模式时,我想显示输入字段而不是文本字段,为此,我正在使用可见绑定.因此,我需要为它们中的每一个提供一个布尔值.

I want to show input fields instead of text fields when the object is in edit mode, for this I am using the visible binding. So I need a Boolean observable for each of them.

如何在不知道列表中元素数量的情况下执行此操作...我也有添加和删除操作,因此每次创建新元素时,都需要向此数组添加更多可观察对象.

How can I do this without knowing the amount of elements in the list... I also have add and delete, so I would need to add more observables to this array each time a new element is created.

我也试图给我的对象赋予一个ko.observable元素,但是我做不到.

I also tried to give a ko.observable element to my objects but I could not do this.

推荐答案

我喜欢在observableArray内部使用一个对象.这是一个内联编辑功能的示例,该功能可根据需要添加许多行.

I like to use an object inside the observableArray. Here is an example of an inline edit feature for as many many rows as needed.

function Employee(emp) {
  var self = this;
  self.Name = ko.observable(emp.Name);
  self.Age = ko.observable(emp.Age);
  self.Salary = ko.observable(emp.Salary);
  self.EditMode = ko.observable(emp.EditMode);
  self.ChangeMode = function() {
    self.EditMode(!self.EditMode());
  }
}

function viewModel() {
  var self = this;
  self.Employees = ko.observableArray()
  self.Employees.push(new Employee({
    Name: "Joe",
    Age: 20,
    Salary: 100,
    EditMode: false
  }));

  self.Employees.push(new Employee({
    Name: "Steve",
    Age: 22,
    Salary: 121,
    EditMode: false
  }));

  self.Employees.push(new Employee({
    Name: "Tom",
    Age: 24,
    Salary: 110,
    EditMode: false
  }));
}
var VM = new viewModel();
ko.applyBindings(VM);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table border=1>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Salary</th>
      <th></th>
    </tr>
  </thead>
  <tbody data-bind="foreach: Employees">
    <tr data-bind="if: !EditMode()">
      <td data-bind="text: Name"></td>
      <td data-bind="text: Age"></td>
      <td data-bind="text: Salary"></td>
      <td><button data-bind="click: ChangeMode">Edit</button></td>
    </tr>
    <tr data-bind="if: EditMode()">
      <td>
        <input data-bind="value: Name">
      </td>
      <td>
        <input data-bind="value: Age">
      </td>
      <td>
        <input data-bind="value: Salary">
      </td>
      <td><button data-bind="click:ChangeMode">Save</button></td>
    </tr>
  </tbody>
</table>

这篇关于我怎样才能创建一个基因敲除的观察值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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