Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind querystring parameters using Knockout.js?

Tags:

knockout.js

I have the following code:

<div data-bind="foreach: roomba">
  <h3 data-bind="text: name"></h3>
  <a href="/arena/bots/status?id=1234">View Status</a>
</div>

My dilemma is that I'd like the id parameter in the anchor tag to be bound to the id of the roomba currently being iterated over. How do I do this?

like image 901
David Smith Avatar asked Feb 13 '12 15:02

David Smith


People also ask

How do you bind a click event in Knockout?

The function you want to bind to the element's click event. You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject. someFunction .

What is binding in knockout JS?

A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.

What is $data in Knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.


2 Answers

Try Defining the URL in the view binding. Then bind to that url in data-bind="attr"

Take a look at this example:

<ul id="MemberSearch" data-inset="true" data-bind="foreach: members">    
<li> <a  data-bind="attr: { href:Url},text:Name"></a></li>
</ul>

Then in your model

function Member(data) {
            this.Name = ko.observable(data.FirstName + ' ' + data.LastName);
            this.Url = ko.observable("/member/details/"+data.Id);
        }
like image 200
Calgary Libertarian Avatar answered Oct 21 '22 16:10

Calgary Libertarian


You should be able to do it as

<a data-bind="attr: { href: '?id=' + $data.id}"></a>

Worked for my example anyway

like image 24
Manatherin Avatar answered Oct 21 '22 14:10

Manatherin