【问题标题】:knockout.js computed array not firing on changeknockout.js 计算数组未在更改时触发
【发布时间】:2013-02-07 11:18:15
【问题描述】:

我正在尝试使用 MVC 4 和 Knockout.js 中的计算 observableArray 创建可编辑网格。首次加载数组时会调用 computed() 方法,但不会在通过用户编辑更改网格上的任何数据时调用。

视图模型:

function CarsVm() {
var self = this;

self.url = 'http://localhost/FederatedWcf/Services/RestCars.svc/json/cars';

self.cars = ko.observableArray([]);

self.car = ko.computed(function () {
    if ( this.cars().length > 0)
        return this.cars()[this.cars().length-1].Make;
    else {
        return "";
    }
}, this);

self.GetCars = function () {
    var count = 0;
    $.getJSON(self.url, function (allData) {
        var mappedCars = $.map(allData.JsonCarsResult, function (item) {
            console.log(count);
            console.log(item);
            count = count + 1;
            return new Cars(item);
        });
        self.cars(mappedCars);
        console.log(self.cars());
    });
    $.ajaxSetup({ cache: false });
};

}

还有html片段:

<table>
<thead>
    <tr>
        <th></th>
        <th>Year</th>
        <th>Make</th>
        <th>Model</th>
        <th></th>
    </tr>
</thead>
<tbody data-bind="foreach: cars">
    <tr>
        <td><span style="display:none" data-bind="text:Id"></span></td>
        <td><input data-bind="value:Year"></input></td>
        <td><input data-bind="value:Make"></input></td>
        <td><input data-bind="value:Model"></input></td>
        <td><button data-bind="click: $root.removeCar">-</button></td>
    </tr>
</tbody>
</table>
<span data-bind="text:car"></span>

如果我编辑网格中的最后一个 Make,我希望数据绑定的汽车元素会更新,但事实并非如此。

如何检测网格上的变化,例如在 onblur 事件期间,在淘汰的 observableArray 中?

【问题讨论】:

    标签: knockout.js computed-observable


    【解决方案1】:

    确保将 Cars 中的每个属性标记为可观察或淘汰赛不会注意到它们发生了变化。

    function Cars(data) {
       var self = this;
       self.Id = data.Id;
       self.Year = ko.observable(data.Year);
       self.Make = ko.observable(data.Make);
       self.Model = ko.observable(data.Model);
    }
    

    【讨论】:

      【解决方案2】:

      这是因为当您更改cars 中对象的属性 时,observableArray 不会观察到任何东西(它仍然包含相同的对象,对吧?)

      要让它知道属性,你必须让 observableArray 中的每个项目本身成为 observable。您可以在当前映射函数中使用自己的mapping plugin 或手动使用ko.observable() 进行剔除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-09
        • 2014-09-22
        • 2016-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-08
        相关资源
        最近更新 更多