绑定到现有静态数据的建议方法是什么?我必须将它包含在视图模型中,因为它用于计算值。
<div id="sum" data-bind="text: sum">
</div>
<div class="line">
dynamic: <span data-bind="text: dynamicValue"></span>
static: <span data-bind="text: staticValue">312</span>
<button data-bind="click: getDataFromServer">get data</button>
</div>
<div class="line">
dynamic: <span data-bind="text: dynamicValue"></span>
static: <span data-bind="text: staticValue">123</span>
<button data-bind="click: getDataFromServer">get data</button>
</div>
</p>
function SumViewModel(lines){
this.sum = ko.computed(function(){
var value = 0;
$.each(lines, function(index, element){
var staticValue = element.staticValue();
if (staticValue)
value += staticValue;
var dynamicValue = element.dynamicValue();
if (dynamicValue)
value += dynamicValue;
value += dynamicValue;
});
return value;
});
}
function LineViewModel() {
this.randomNumber = function(max) {
return Math.floor((Math.random() * max) + 1);
};
this.dynamicValue = ko.observable(0);
this.staticValue = ko.observable();
this.getDataFromServer = function() {
this.dynamicValue(this.randomNumber(300));
};
};
var lines = [];
$('.line').each(function(index, element) {
var line = new LineViewModel()
//line.staticValue(parseInt($('[data-bind*="staticValue"]', element).text()));
lines.push(line);
ko.applyBindings(line, element);
});
var sum = new SumViewModel(lines);
ko.applyBindings(sum, $('#sum')[0]);
</p>