javascript - 基于外部数组Knockout JS的计算属性

标签 javascript html knockout.js

我刚刚开始使用 Knockout 并完成多元站点类(class)。 我有一个关于基于父数组的计算属性的(大概是基本的)问题:

鉴于以下代码,我如何使其工作,以便 my.vm.attendees 中每个项目的 Amount 属性始终为 totalCost 除以与会者人数。例如。参加人数为 4 人,每人的募集金额应为 25。 当您添加和删除项目时,这应该会自动更新。

<script type="text/javascript">
    $(function () {
        var total = 100;

        //Attendee construction
        my.Attendee = function () {
            this.Name = ko.observable();
            this.Amount = ko.computed(function () {
                return total / this.numberOfAttendees;
            }, my.vm);
        };

        my.vm = {
            //observable array of attendees
            attendees: ko.observableArray([new my.Attendee()]),
            addAttendee: function () {
                my.vm.attendees.push(new my.Attendee());
            },
            numberOfAttendees: function () {
                my.vm.attendees.lenght + 1; //zero based
            }
        }

        ko.applyBindings(my.vm);
    });
</script>

最佳答案

我可能会做这样的事情。

function attendee(name, amount) {
  var self = this;
  this.name = ko.observable(name);
  this.amount = ko.observable(amount);
}

function model() {
  var self = this;
  this.attendees = ko.observableArray();
  this.total = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.attendees(), function(item) {
      var value = parseFloat(item.amount());
      if (!isNaN(value)) {
        total += value;
      }
    });
    return total.toFixed(2);
  }, this);
  this.average = ko.pureComputed(function() {
    return self.total() / self.attendees().length;
  }, this);
  this.remove = function(row) {
    self.attendees.remove(row);
  }
  this.name = ko.observable('');
  this.amount = ko.observable('');
  this.add = function() {
    self.attendees.push(new attendee(self.name(), self.amount()));
    self.amount('');
    self.name('');
  }
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
  mymodel.attendees.push(new attendee('Bob', 25));

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
  <thead>
    <tr>
      <th>Name</th>
      <th>Amount</th>
      <td>Delete</td>
    </tr>
  </thead>
  <tbody data-bind="foreach: attendees">
    <tr>
      <td data-bind="text:name"></td>
      <td data-bind="text:amount"></td>
      <td>
        <button class="btn btn-danger" data-bind="click: $parent.remove">
          X
        </button>
      </td>
    </tr>
  </tbody>
  <tfooter>
    <tr>
      <td colspan=2>Average:
        <span data-bind="text:average">
        </span>
      </td>
    </tr>
  </tfooter>
</table>

<form class="form form-inline">
  <label class="sr-only" for="inlineFormInput">Name</label>
  <input type="text" class="form-control" id="inlineFormInput" placeholder="enter name" data-bind="textInput: name">

  <label class="sr-only" for="inlineFormInputGroup">Amount</label>
  <div class="input-group ">
    <div class="input-group-addon">$</div>
    <input type="text" class="form-control" id="inlineFormInputGroup" placeholder="amount" data-bind="textInput: amount">
  </div>


  <button type="buttont" class="btn btn-primary" data-bind="click: add">add row </button>
</form>

关于javascript - 基于外部数组Knockout JS的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577816/

相关文章:

javascript - 我的 html5 自定义音频控件遇到一些问题

javascript - Chrome 扩展程序 : callback function not getting called

html - WP 背景图像显示在内容区域之后

html - flex 盒布局 : shrink and grow at the same time

javascript - TypeError : data. itemNo 不是函数

javascript - 无法 .empty() 附加元素

javascript - ajax 正在加载页面以返回 POST 请求

javascript - 如何包含外部 HTML-Head?

javascript - 如何在knockout js中获取json响应?

javascript - dotVVM 将值从数据绑定(bind)的 DOM 元素传递到 JavaScript 变量以进行可视化