Patrice Calvé
Patrice Calvé

Reputation: 684

knockout.js, jquery-ui, button click and param

I'm using jQuery UI to create a "button" to a given html element. I'm using Knockout.js to generate the html element (foreach).

However, I can't find the way how to pass a parameter to the click event for knockout.js generated items. In the following example, the somewhat static sampleButton works, but not the itemButton items. http://jsfiddle.net/patware/QVeVH/

function ViewModel() {
    var self = this;

    self.ping = 'pong';

    self.items = ko.observableArray([
        { display: 'Cars', id: 1 },
        { display: 'Fruits', id: 2 },
        { display: 'Humans', id: 3 },
        { display: 'Software', id: 4 },
        { display: 'Movies', id: 5 },
    ]);
}

ko.applyBindings(new ViewModel());

$("#sampleButton").button().data('someData',101);
$("#sampleButton").click(function(e){
    alert('clicked sample: [' + $(this).data('someData') + ']');
});

$(".itemButton").button().data('someData',$(this).id);

$(".itemButton").click(function(){
    alert('clicked item: [' + $(this).attr('foo') + ']');
});

ping-<span data-bind="text: ping"></span>

<div id="sample">
<div id="sampleButton">
    <h3>Sample Button</h3>
    <a href="#">Click here too</a>
</div>
</div>

<div data-bind="foreach: items">
<div class="itemButton" data-bind="foo: id">
    <h3 data-bind="text:display"></h3>
    <a href="#" data-bind="text:display"></a>
</div>
</div>​

Upvotes: 0

Views: 2464

Answers (2)

John Earles
John Earles

Reputation: 7194

You can set everything up using a custom binding.

http://jsfiddle.net/jearles/QVeVH/7/

Upvotes: 1

Artem
Artem

Reputation: 3700

Consider using ko.dataFor instead of applying data with jquery. Working sample based on your example http://jsfiddle.net/QVeVH/6/

Upvotes: 1

Related Questions