Search code examples
knockout.jsupshot

how to bind something to a function in knockout.js


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?


Solution

  • 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.