0

我在 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代码

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 数据(工作)

{"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?

4

2 回答 2

3

当您处于foreach循环中时,范围是您正在循环的数组项。您的视图模型已NameAbbreviation在根级别而不是在每个项目上定义。

您可以在此处采用多种方法。

最简单的方法是在您的视图模型上创建一个简单的函数,该函数返回格式化的字符串并使用$rootor绑定它$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>

否则,您可以考虑创建一个“项目”构造函数,该函数添加NameAbbreviation然后通过构造函数发送每个原始数据项。

另一种选择是使用映射插件

于 2013-01-23T03:21:29.037 回答
0
// use () with item.Name and item.Abbreviation as below

this.NameAbbreviation = function (item) {
        return item.Name() + " " + item.Abbreviation();
    };
于 2013-01-23T07:32:51.350 回答