映射无法使用api调用

时间:2015-06-05 06:22:42

标签: knockout.js knockout-mapping-plugin

我想让所有内部员工属性都是可观察的,所以我尝试了淘汰映射插件。但是,在使用它之后数据没有被正确绑定。这是javascript代码:

var employeeViewModel = new function () {
    var self = this;
    self.employees = ko.observableArray();
    self.loading = ko.observable(true);
}();

$(document).ready(function () {
    ko.applyBindings(employeeViewModel);
    GetEmployees();
});

function GetEmployees()
{
    $.get('/api/Employees', null, function (data) {
        if (employeeViewModel.employees.length == 0) {
            employeeViewModel.employees = ko.mapping.fromJS(data);
        }
        else {
            ko.mapping.fromJS(data, employeeViewModel.employees);
        }
        //employeeViewModel.employees(data); //This works but want to make all inner properties as observable
        employeeViewModel.loading(false);
    });
}

HTML代码:



<div class="loadingImg" data-bind="visible: loading()"></div>
<table class="table table-bordered" data-bind="visible: !loading()">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody data-bind="foreach:employees">
        <tr data-bind="template: {name: 'edit-template', data: $data }"></tr>
    </tbody>
</table>

<script type="text/html" id="display-template">
    <td data-bind="text: Name"></td>
    <td data-bind="text: Email"></td>
    <td data-bind="moneyFormat: Salary"></td>
</script>
<script type="text/html" id="edit-template">
    <td><input class="form-control" type="text" data-bind="value: Name" /></td>
    <td><input class="form-control" type="text" data-bind="value: Email" /></td>
    <td><input class="form-control" type="text" data-bind="value: Salary" /></td>
</script>
&#13;
&#13;
&#13;

主要问题是它出现但没有以某种方式绑定。结果如下: -

enter image description here

下面的代码有效,但如何通过映射插件实现相同的功能? 我认为我们可以通过映射插件在一行中做同样的事情,但它不起作用。!!需要帮助..可能是我在这里遗漏了一些东西..

&#13;
&#13;
        employeeViewModel.employees(ko.utils.arrayMap(data, function (employee) {
            var obsEmployee = {
                Name: ko.observable(employee.Name),
                Email: ko.observable(employee.Email),
                Salary: ko.observable(employee.Salary)
            }
            return obsEmployee;
        }
        ));
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

不要创建employees observableArray。它受到applyBindings的约束,然后您从ko.mapping.fromJS重新分配它。您需要使用if绑定而不是visible来阻止敲除在映射和绑定之前尝试访问员工。

<table class="table table-bordered" data-bind="if: !loading()">

示例:http://jsfiddle.net/qxc19joy/