Knockout observable array Change Event

时间:2015-10-16 10:51:08

标签: jquery knockout.js

我有observableArray observable properties。我想在添加项目/项目的任何属性更改时设置observableArray项目的状态。

function ViewModel() {
this.myArray=ko.observableArray([]);
}
var viewModel = new ViewModel();
    $(function(){
        ko.applyBindings(viewModel);
        viewModel.myArray.push({Value1:ko.observable("Test"),Value2:ko.observable("Test1"),Status:ko.observable('Added')});

});

每当observableArray项目被修改(From UI or from Code)时,我想fire change event使用该项目。

例如:从代码修改

viewModel.myArray()[0].Value1("newTest1");  // At this point i need change event with changed array item.

请建议我如何实现这一目标。我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用某些(私有)计算字段,您将迭代所需的所有可观察属性。 如果稍后会对此计算内的某些内容进行更改,则会重新计算该内容,您将收到通知

ko.computed(function(){
    viewModel.collection().forEach(function(element){
        var a = element.text();
    });
}

在此示例中,当更改数组或更改任何元素文本时,将重新计算整个计算,并且您可以在此处设置一些所需的状态

答案 1 :(得分:0)

如上面的评论中所述,您需要订阅observable而不是尝试订阅observableArray(因为只有在添加/删除某些内容时才会收到通知)。

<强>视图模型:

function child(data) {
    var self = this;
    self.Value1 = ko.observable(data.Value1);
    self.Value2 = ko.observable(data.Value2);
    self.Status = ko.observable(data.Status);
    ko.computed(function () {
        self.Value1();
        self.Value2(); // subscribing multiple observables
        if (!ko.computedContext.isInitial()) { //status remains intact initially(onLoad)
            self.Status('Modified');
        }
    });
}

function ViewModel() {
    var self = this;
    self.myArray = ko.observableArray([]);
}
$(function () {
    ko.applyBindings(new ViewModel());
});

工作样本 here

您可以在上面找到我正在使用功能computedContext

isInitial
  

isInitial() - 在第一个函数中调用时返回true的函数   曾经评估当前计算的可观察量,或者是假的   除此以外。对于纯计算的observable,isInitial()始终是   未定义。

计算文档here

相关问题