Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Arbiter Avatar asked Feb 22 '12 21:02

Arbiter


2 Answers

I've been working through very similar issues and I've found that you can intercept the creation of the Broker objects and insert your own fields using the mapping options parameter:

var data = { "Brokers":[{"BrokerNum": "2"},{"BrokerNum": "10"}] };

var mappingOptions = {
    'Brokers': {
        create: function(options) {
            return (new (function() {
                this.Url = ko.computed(function() {
                    return 'http://BASEURLHERE/' + this.BrokerNum();
                }, this);

                ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
            })());
        }
    }
};

viewModel = ko.mapping.fromJS(data, mappingOptions);

ko.applyBindings(viewModel);

Here is a fiddle to demonstrate this: http://jsfiddle.net/pwiles/ZP2pg/

like image 61
Peter Wiles Avatar answered Oct 21 '22 04:10

Peter Wiles


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>
like image 25
Roman Bataev Avatar answered Oct 21 '22 05:10

Roman Bataev