Search code examples
javascriptmvvmknockout.jsknockout-mapping-plugin

KnockoutJS - Adding computed values to an observable array


I'm binding data to a page using KnockoutJS, the ViewModel is being populated by an JSON response from an AJAX call using the mapping plugin, like this:

$(function () {
    $.getJSON("@Url.Action("Get")", 
        function(allData) {
            viewModel = ko.mapping.fromJS(allData);

            viewModel.Brokers.Url = ko.computed(function()
            {
                return 'BASEURLHERE/' + this.BrokerNum();
            });

            ko.applyBindings(viewModel);
    });
});

The middle part there doesn't work (it works fine without that computed property). "Brokers" is an observable array, and I want to add a computed value to every element in the array called URL. I'm binding that Brokers array to a foreach, and I'd like to use that URL as the href attribute of an anchor. Any ideas?


Solution

  • Well, if you want Url in each broker, you have to add it to each broker:

    $.each(viewModel.Brokers(), function(index, broker){
        broker.Url = ko.computed(function(){return 'BASEURLHERE/' + broker.BrokerNum();});
    });
    

    I guess BrokerNum is not going to change, so you might as well just calculate Url once:

    $.each(viewModel.Brokers(), function(index, broker){
        broker.Url = 'BASEURLHERE/' + broker.BrokerNum();
    });
    

    You can also add Url property during mapping by providing "create" callback to ko.mapping.fromJS function. See mapping plugin docs for details.

    If you only need url to bind to href, just bind the expression in html (within foreach binding):

    <a data-bind="attr: {href: 'BASEURLHERE/' + BrokerNum()}">link to broker details</a>