knockout.js绑定到静态数据

时间:2012-06-13 08:55:02

标签: knockout.js

绑定到现有静态数据的建议方法是什么?我必须在viewmodel中包含它,因为它在计算值中使用。

http://jsfiddle.net/z2ykC/4/

<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>

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]);

2 个答案:

答案 0 :(得分:2)

您可以查看创建自定义绑定,它将初始化staticValue observable。这是一个工作小提琴:

http://jsfiddle.net/z2ykC/6/

答案 1 :(得分:1)

您的视图效率低下,最好使用foreach绑定来渲染线条。如果您需要viewmodel中的数据,它属于viewmodel,或者应该从服务器获取。不要放入视图并将其解压缩。

function SumViewModel(lines) {
    // ...
    this.lines = lines;
}

function LineViewModel(staticValue) {
    // ...
    this.staticValue = ko.observable(staticValue);
}

var staticValues = [312, 123];
var lines = [];

$.each(staticValues, function(index, value) {
    lines.push( new LineViewModel(value) );
});

ko.applyBindings( new SumViewModel(lines) );

http://jsfiddle.net/z2ykC/5/