如果数据绑定对象只有它的名称,那么敲除如何知道它

How knockout know about data-binded object if it has only its name?

本文关键字:何知道 对象 数据绑定 如果      更新时间:2023-10-06

我有这样的东西:

<form action='/someServerSideHandler'>
  <p>You have asked for <span data-bind='text: gifts().length'>&nbsp;</span> gift(s)</p>
  <table data-bind='visible: gifts().length > 0'>
    <thead>
      <tr>
        <th>Gift name</th>
        <th>Price</th>
        <th />
      </tr>
    </thead>
    <tbody data-bind='foreach: gifts'>
      <tr>
        <td><input class='required' data-bind='value: name, uniqueName: true' /></td>
        <td><input class='required number' data-bind='value: price, uniqueName: true' /></td>
        <td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>
      </tr>
    </tbody>
  </table>
  <button data-bind='click: addGift'>Add Gift</button>
  <button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
</form>

var GiftModel = function(gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.addGift = function() {
  self.gifts.push({
    name: "",
    price: ""
  });
};
self.removeGift = function(gift) {
  self.gifts.remove(gift);
};
self.save = function(form) {
  alert("Could now transmit to server: " + ko.utils.stringifyJson(self.gifts));
  // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.gifts);
};
};
var viewModel = new GiftModel([
    { name: "Tall Hat", price: "39.95"},
    { name: "Long Cloak", price: "120.00"}
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });

ko.applyBindings(viewModel);是如何神奇地通过变量的名称进行投标的?淘汰赛是以某种方式按名字搜索它吗?模板如何知道这是他的数组/数据集?我基本上是.net的开发人员,所以在我的脑海中"按名称"取一些东西并不清楚。或者我错了,这是按名字写的?我阅读了文档,但我仍然不明白如何将模板gifts()与模型中的数组命名gifts进行敲除连接?

但这是来自淘汰赛主页的样本。

http://knockoutjs.com/examples/gridEditor.html

ko.applyBindings(viewModel);是神奇地通过变量的名称进行投标吗?淘汰赛是以某种方式按名字搜索它吗?

在这里偷工减料,但Javascript(没有太多KO)与.NET的两个不同之处与您的问题有关:

  • 所有成员(例如self.gifts)也可以被访问,就好像self有一个基于字符串的索引器来获取它们一样(例如,self['gifts']
  • Javascript是动态类型的,所以self['gifts']在运行时可以包含一个数组、字符串、observable:随便什么

因此,Knockout可以将字符串"gifts"用于变量self["gifts"],并在运行时检查其类型,以查看它是否是数组、可观察y/n等,并相应地选择适当的代码路径。

至于你的另一个问题:

模板如何知道这是他的数组/数据集?

Knockout是开源的(尽管从JS开始可能不容易阅读),如果深入研究它,你会发现foreach假设它传递了一个数组。