0

I am using knockout.js and upshot.js to get a list of items from API controller on the server. This is basically my view model:

self.templatesDataSource = upshot.dataSources.Templates.refresh();
self.templates = self.templatesDataSource.getEntities();

Binding to properties works just fine:

<div data-bind="foreach: templates">
    <a href="#" data-bind="text: Title"></a><br />
</div>

But let's say I want the text to not only display the title, but a combination of the title and some other value? Let's say I want Title + ' ' + Id. Based on "example 4" from here, I'm thinking I should be able to do something like this:

<div data-bind="foreach: templates">
    <a href="#" data-bind="text: function(item){return item.Title + ' ' + item.Id; }"></a><br />
</div>

However, I see the function text (function(item){...etc) instead of result. I would also need this functionality to construct proper href for the link. How can I accomplish this?

Alex Polkhovsky
  • 3,340
  • 5
  • 29
  • 37

1 Answers1

2

you can just write your statement directly like:

data-bind="text: Title + " " + Id"

If your properties are observables, then you would do:

data-bind="text: Title() + " " + Id()"

For binding against href you would do:

data-bind="attr: { href: Url }"

The other option when you are calculating a value is to use a computed observable to represent the value.

RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211
  • data-bind="text: Title + ' ' + Id" resulted in a long compressed javascript function as output. However, using data-bind="text: Title() + ' ' + Id()" produced desired result. Whatever upshot.js returns as datasource is indeed observable. Thank you!!! – Alex Polkhovsky May 03 '12 at 02:42