<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Ko Test</title>
</head>
<body>
<h1>方法1</h1>
<ul data-bind="foreach: fruits">
<li data-bind="click: $root.clickHdr.bind(name), text:name + ‘(点击)‘"></li>
</ul>
<h2>方法2</h2>
<ul data-bind="foreach:fruits">
<li data-bind="click: $root.clickHdr2.bind({name:name}), text:name + ‘(点击)‘"></li>
</ul>
<h3>方法3</h3>
<ul data-bind="foreach: fruits">
<li data-bind="click: function() {$root.clickHdr3(name);}, text:name + ‘(点击)‘"></li>
</ul>
<h4>方法4</h4>
<ul data-bind="foreach: fruits">
<li data-bind="click:$root.clickHdr4, text:name + ‘(点击)‘"></li>
</ul>
<script src="js/knockout-3.1.0.js"></script>
<script>
var myViewModel = {
fruits: [
{ id: 1, name: ‘苹果‘ },
{ id: 2, name: ‘梨子‘ },
{ id: 3, name: ‘香蕉‘ },
{ id: 4, name: ‘萄萄‘ }
],
clickHdr:function(){
alert(this);
},
clickHdr2: function () {
alert(this.name);
},
clickHdr3: function (name) {
alert(name);
},
clickHdr4: function (obj) {
alert(‘this.id is ‘ + this.id + ‘\n\
obj.id is ‘ + obj.id + ‘\n\
this === obj is ‘ + (this === obj)
);
}
};
ko.applyBindings(myViewModel);
</script>
</body>
</html>
原文地址:http://yhj200722.blog.51cto.com/3276916/1558608