2014-03-03 129 views
1

我有一个observableArray和一个observable如下。更新ObservableArray中的可观察值knockoutjs

self.unreadcount = ko.observable(); 

self.searchFilters = ko.observableArray([ 
    {label: "A", active: ko.observable(false), count1: self.unreadcount()}, 
    {label: "B", active: ko.observable(false), count1: self.unreadcount()}, 
    {label: "C", active: ko.observable(false), count1: self.unreadcount()} 
]); 

在一个特定的功能,我已经过了一定的参考价值self.unreadcount(), 我需要更新我的observableArray还我accordingly.How能做到吗?

+0

添加的jsfiddle演示。 – alexmac

回答

1

您可以使用self.unreadcount可观察值来设置count1属性。

self.searchFilters = ko.observableArray([ 
    {label: "A", active: ko.observable(false), count1: self.unreadcount}, 
    {label: "B", active: ko.observable(false), count1: self.unreadcount}, 
    {label: "C", active: ko.observable(false), count1: self.unreadcount} 
]); 

See fiddle

或者可以将绑定在count1属性的$parent.unreadcount

<div data-bind="foreach : searchFilters"> 
    <span data-bind="text : label"></span> 
    <span data-bind="text : $parent.unreadcount"></span> 
    <br/> 
</div> 

JS

var VM = function() { 
    var self = this; 
    self.unreadcount = ko.observable(); 

    self.searchFilters = ko.observableArray([ 
    {label: "A", active: ko.observable(false)}, 
    {label: "B", active: ko.observable(false)}, 
    {label: "C", active: ko.observable(false)} 
    ]); 
}; 

See fiddle

如果您需要手动更新count1;你可以这样做:

self.searchFilters = ko.observableArray([ 
    {label: "A", active: ko.observable(false), count1: ko.observable(self.unreadcount())}, 
    {label: "B", active: ko.observable(false), count1: ko.observable(self.unreadcount())}, 
    {label: "C", active: ko.observable(false), count1: ko.observable(self.unreadcount())} 
]); 

self.update = function(newValue) { 
    ko.utils.arrayForEach(self.searchFilters(), function(row) { 
     row.count1(newValue); 
    }); 
} 

See fiddle

1

我不知道这是否是你所追求的,但我已经创建了一个的jsfiddle:http://jsfiddle.net/RFc3r/2/,它使用您的observableArray,并允许您更新每行计数。

标记:

<p data-bind="text: ko.toJSON(searchFilters)"></p> 
<div class="liveExample" data-bind="foreach: searchFilters"> 
    <p>Label:<input data-bind="value: label"></input></p> 
    <p>Active:<input type="checkbox" data-bind="checked: active"></input></p> 
    <p>Unread:<input data-bind="value: count1"></input></p> 
    <input type="button" data-bind="click: changeValue(count1)" value="click me"/> 
    <hr/> 
</div> 

JS:

var ViewModel = function() { 
    self.unreadcount = ko.observable(0); 

    self.searchFilters = ko.observableArray([{ 
     label: "A", 
     active: ko.observable(false), 
     count1: ko.observable(self.unreadcount()) 
    }, { 
     label: "B", 
     active: ko.observable(true), 
     count1: ko.observable(self.unreadcount()) 
    }, { 
     label: "C", 
     active: ko.observable(false), 
     count1: ko.observable(self.unreadcount()) 
    }]); 

    self.changeValue = function(item){ 
     item(item() + 1); 
    }; 
}; 

ko.applyBindings(new ViewModel()); 
相关问题