Binding Anchor Href to Generated Function Result

1,449 views
Skip to first unread message

jakew...@gmail.com

unread,
Dec 22, 2011, 8:57:50 AM12/22/11
to knock...@googlegroups.com
I am using the Play Framework and transitioning to use Knockout 2.0 which has thus far been awesome. One thing that I wanted to change was how I handle links. Presently I was storing the ID in a data attribute and using jQuery live-binding to create click handlers which would redirect to the appropriate URL substituting in the ID.

The Play Framework generates pure javascript functions from your routes file which construct links based on a series of parameters.

var searchAction = #{jsAction @Search.index(':query') /}

In the code you can then call searchAction({query: 'whatever'}) to get the appropriate URL.

What I'd like to figure out is a way to bind to these automatically generated functions without adding a ko.computed to the array item model. That is, I only define a ko.observableArray([]) in my model and then set it to an array returned from AJAX. I'd like to not have to explicitly define a model for these items.

Is there any way for me to perform this binding?

Here's a demo of what I want: http://jsfiddle.net/gQspX/1/. The /some/url/??? is what I would like replaced with a call to the searchAction method with the corresponding ID. I would prefer to retain assigning the href attribute to allow for middle-clicking to open in new tabs.

rpn

unread,
Dec 22, 2011, 9:42:26 AM12/22/11
to knock...@googlegroups.com
You should be able to do something like this:  

<li><data-bind="text: name, attr: { href: searchAction({id: id}) }"></a></li> 


Does that work for your scenario?

Jake Wharton

unread,
Dec 22, 2011, 10:25:57 AM12/22/11
to knock...@googlegroups.com
Yes, that works provided the function is in the global context (which I don't mind). Despite providing an accurate example of how to call the function I was trying to pass in only the ID rather than wrapping it in an object in my code which is why it wasn't working.

Thanks for taking a look.

Koviko

unread,
Dec 22, 2011, 11:51:29 AM12/22/11
to knock...@googlegroups.com
You can move the function into a different scope. You can place it into your viewModel and access it via $root.

Jake Wharton

unread,
Dec 22, 2011, 2:19:02 PM12/22/11
to knock...@googlegroups.com
Oooo I like that very much. Initially tried to use $parent but realized that wouldn't work.

Thanks!
Reply all
Reply to author
Forward
0 new messages