2012-03-22 79 views
0

我正在使用jQuery UI为给定的HTML元素创建一个“按钮”。我使用Knockout.js来生成html元素(foreach)。knockout.js,jquery-ui,按钮单击和参数

但是,我找不到如何将参数传递给knockout.js生成项目的click事件的方式。在下面的例子中,稍微静态的sampleButton工作,但不是itemButton项目。 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>​ 

回答

1

考虑使用ko.dataFor代替与jquery施加的数据。 基于您的示例的工作示例http://jsfiddle.net/QVeVH/6/

+0

还使用坏线为KO-生成的链接设置数据,在此行'$( “itemButton”)。按钮()。数据( 'someData',$(本).ID );',这里$(this)将评估为$(window) – Artem 2012-03-22 23:25:02