user471317
user471317

Reputation: 1231

Knockout - accessing variable properties

I have a viewmodel that looks something like this.

function ViewModel()
{
    this.Regions = ['Europe', 'AsiaPac', 'Americas'];

this.Sales = { 
    EuropeRevenue: 100, 
    EuropeProfit: 100, 
    AsiaPacRevenue: 200, 
    AsiaPacProfit: 100,
    AmericasRevenue: 300,
    AmericasProfit: 250
};
}

I have to print out each of the Regions, followed by their Revenue and Profit.

How do I do that? Loop through the regions and for each region do Sales.[Region]Revenue and Sales.[Region]Profit.

    <div data-bind="foreach: Regions }">
        Region:<span data-bind="text: $data"></span>
        Revenue:<span data-bind="text: $root.Sales.$dataRevenue???"></span>
        Profit:<span data-bind="text: $root.Sales.$dataProfit???"></span>
    </div>

Thanks.

Upvotes: 0

Views: 441

Answers (1)

nemesv
nemesv

Reputation: 139748

Your data setup is very strange, so if you can change it I would suggests to model this with a RegionSales collection...

this.RegionSalesData = 
        [ 
            { Name: 'Europe', Revenue: 100, Profit: 100},
            { Name: 'AsiaPac',Revenue: 200, Profit: 100},
            { Name: 'Americas', Revenue: 300, Profit: 250}];

Then you can use in the binding the Name, Revenue, Profit properties.

But to answer your actual question: in JavaScript you can access properties by name with the [] syntax, so you can generate the property names in your binding with a simple string concat:

<div data-bind="foreach: Regions ">
    <div>
        Region:<span data-bind="text: $data"></span>
        Revenue:<span data-bind="text: $root.Sales[$data+'Revenue']"></span>
        Profit:<span data-bind="text: $root.Sales[$data+'Profit']"></span>
    </div>
</div>

Demo JSFiddle.

Upvotes: 2

Related Questions