我在KnockOutJS ViewModel中创建自定义字段时遇到问题。
HTML
<table class="table table-striped">
<thead><tr>
<th>name</th><th>abb</th><th>combo</th>
</tr></thead>
<tbody data-bind="foreach: clients"><tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Abbreviation"></td>
<td data-bind="text: NameAbbreviation"></td>
</tr></tbody>
</table>
JS CODE
function ClientModel() {
var self = this;
// Bind all data to UI < -- working
self.clients = ko.observableArray(data);
// Not working
self.NameAbbreviation = ko.computed(function () {
return self.Name + " " + self.Abbreviation;
})
};
ko.applyBindings(new ClientModel());
JOSN DATA (工作)
{"ID":14,"GUID":"c999b888-9566-2e50-a23c-07913d389f99","Name":"Aaron46","Abbreviation":"Corporate Customer","Website":"www.ts2mkg3d0oomo.com","Email":"kltuh32@otyvmj.net","Active":true,"ModifyDate":"1959-02-14T15:47:53.43","CreatedDate":"1987-09-26T00:37:13.52","CreatedDateString":"9/26/1987","ModifyDateString":"2/14/1959","Status":0,"Message":null},{"ID":443,"GUID":"12c60aa5-03f1-509c-5d49-9caf696c44ce","Name":"Abigail","Abbreviation":"Technical","Website":"www.wsfj97qccj1.com","Email":"eagai@odgqur.com","Active":true,"ModifyDate":"2007-02-01T06:01:11.3","CreatedDate":"1963-05-11T01:23:21.11","CreatedDateString":"5/11/1963","ModifyDateString":"2/1/2007","Status":0,"Message":null},{"ID":136,"GUID":"63c65e85-0f9b-1f7c-328a-ca253a4881d1","Name":"Adrienne","Abbreviation":"Accounting","Website":"www.ixug6k4eqkjmnr.com","Email":"tqxcjexh.izoiqv@pyuzqk.net","Active":false,"ModifyDate":"2000-12-14T08:11:31.83","CreatedDate":"1980-05-03T03:25:02.34","CreatedDateString":"5/3/1980","ModifyDateString":"12/14/2000","Status":0,"Message":null}
当我不创建自定义视图字段时,我能够无问题地绑定所有数据!
当我尝试创建 NameAbbreviation 自定义字段时,出现错误
Error: Unable to parse bindings.
Message: ReferenceError: NameAbbreviation is not defined;
Bindings value: text: NameAbbreviation
我理解错误,因为KO在视图中找不到NameAbbreviation。
如何获取KO使用/看到的自定义视图NameAbbreviation?
答案 0 :(得分:3)
当您处于foreach
循环中时,范围是您循环的数组项。您的视图模型在根级别定义NameAbbreviation
,而不是在每个项目上定义。
您可以在这里采取几种方法。
最简单的方法是在视图模型上创建一个简单函数,该函数返回格式化字符串并使用$root
或$parent
绑定它。
function ClientModel() {
this.clients = ko.observableArray(data);
this.NameAbbreviation = function (item) {
return item.Name + " " + item.Abbreviation;
};
};
然后,在您的UI绑定中:
<tbody data-bind="foreach: clients">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Abbreviation"></td>
<td data-bind="text: $root.NameAbbreviation($data)"></td>
</tr>
</tbody>
否则,您可以考虑创建一个“item”构造函数,该函数添加NameAbbreviation
,然后通过构造函数发送每个原始数据项。
另一种选择是使用mapping plugin。
答案 1 :(得分:0)
// use () with item.Name and item.Abbreviation as below
this.NameAbbreviation = function (item) {
return item.Name() + " " + item.Abbreviation();
};