Ajay Suwalka
Ajay Suwalka

Reputation: 531

How to add a new computed field into knockout view model

I am trying to compute third field in view model.I know this is not the way but just giving the following snippet for example . Please Help

$.ajax({
    type: "GET",
    url: '/ASPNET/GetGroups',
    dataType: "json",
    success: function (data) {
        var viewModel = {
            advisorGroup: ko.observableArray(data)
        };
        viewModel.advisorGroup.label = ko.computed(function () {
            return self.code + ' (' + self.cls+')';
        });
        alert(JSON.stringify(viewModel));
        ko.applyBindings(viewModel);
    }
})


<input type="checkbox" data-bind="attr: { value: code, id: code }" name="GroupsSel" checked="checked">
<label data-bind="attr: { for: code }, text: label "></label>

Upvotes: 1

Views: 607

Answers (1)

codeandcloud
codeandcloud

Reputation: 55248

Try this.

success: function (data) {
    ko.utils.arrayForEach(data, function(item){
        item.label = ko.computed(function () {
            return item.code + ' (' + item.cls + ')';
        });
    });
    //..........
}

Fiddle: http://jsfiddle.net/8WqQu/1/

Or as Anders noted, you could simply do this.

success: function (data) {
    ko.utils.arrayForEach(data, function(item){
        item.label = item.code + ' (' + item.cls + ')';
    });
    //..........
}

Fiddle: http://jsfiddle.net/8WqQu/2/

Upvotes: 1

Related Questions