MatteS
MatteS

Reputation: 1542

knockout.js bind to static data

What's the suggested way to bind to existing static data? I have to include this in the viewmodel because its used in computed values.

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

Upvotes: 3

Views: 4954

Answers (2)

John Earles
John Earles

Reputation: 7194

You could look at creating a custom binding, which would initialize the staticValue observable. Here is a working fiddle:

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

Upvotes: 2

Niko
Niko

Reputation: 26730

Your view is inefficient, better use the foreach binding to render the lines. If you need data in the viewmodel, it belongs in the viewmodel, or should be fetched from the server. Don't put in the view and extract it back.

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/

Upvotes: 1

Related Questions