开发者

Dependent Observable syntax woes

My simple 'dependent observable' does not update and when I give it the syntax of a function as the turorials say is required I get a javascript error. I'm just trying to sum the three observable values.

I开发者_JS百科f I use

<td>${G1 + G2 + G3}</td>

I get a static display: the does not update when the other input fields change.

If I use the viewModel.Series I get no display of values at all. If change viewModel.Series to: this.G1() + this.G2() I get a javascript error saying G1 is NOT a function.

var initialData = {"DateId":32,"Scores":[{"Alias":"Cap Stocks","G1":129,"G2":123,"G3":222,
var theScores = initialData.Scores;
var viewModel = {scores : ko.observableArray(theScores) };
viewModel.Series = ko.dependentObservable(function() {
    return this.G1 + this.G2 + this.G3;
 }, viewModel);
$(function () {
ko.applyBindings(viewModel); }

Here is my template binding that at least displays something

<td> ${Alias}</td>
<td><input data-bind="value: G1"/></td>
<td><input data-bind="value: G2"/></td>
<td><input data-bind="value: G3"/></td>
<td>${G1 + G2 + G3}</td> 


In this case you would need to make the G1, G2, and G3 properties observable. An observableArray notifies when there are changes to the array itself, but not individual properties on its items.

You could use something like the mapping plugin or map it yourself using a constructor function that either takes in a score object or each property.

function Score(alias, g1, g2, g3) {
   this.Alias = alias;
   this.G1 = ko.observable(g1);
   this.G2 = ko.observable(g2);
   this.G3 = ko.observable(g3);

   this.Series = ko.dependentObservable(function() {
       return parseInt(this.G1(), 10) + parseInt(this.G2(), 10) + parseInt(this.G3(), 10);
   }, this);
}

Then, map your existing array:

var theScores = ko.utils.arrayMap(initialData.Scores, function(score) {
    return new Score(score.Alias, score.G1, score.G2, score.G3);    
});

Sample here: http://jsfiddle.net/rniemeyer/SbFDR/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜