2012年9月18日 星期二

Knockoutjs 18-2 Click Binding

Knockoutjs Click Binding

example 帶有引入參入的click handel:

<!DOCTYPE html>
<html>
<head>
<title>click Binding</title>
<meta charset="UTF-8"/>
<style>
*{
margin: 0px 0px 0px 0px;
}
.cube{
text-align: center;
width: 150px;
height:150px;
line-height: 150px;
background-color:#0000FF; /* color is blue*/
color:#FFFFFF;            /* font color is white*/
font-size: 2em;
font-weight: bold;        /*粗體*/
}
</style>
</head>
<body>
<script src="../lib/knockout-2.1.0.js"></script>
<script>
(function(window , undefined ){
var ko = window.ko,
   manager = window.manager || {};

manager.viewModel = {
colors:ko.observableArray(['darkgreen','darkgrey','darkmagenta','darkorange']),
colorIndex:-1,
changeColor:function(data , event){
//被點擊的項目可由event取回
//若需改變其他DOM,則需在init時將需改變的DOM參照記錄於viewModel中
(data.colorIndex >= data.colors().length-1 && (data.colorIndex = -1));
event.srcElement.style.backgroundColor = data.colors()[++data.colorIndex] ;
},
controlName:'Click Me'
};
 
window.manager = manager;  
})(window);

window.onload = function(){
ko.applyBindings( manager.viewModel);
};  
</script>
<div class="cube" id="myCube" data-bind="click:changeColor , text:controlName"></div>
</body>
</html>

參考資料:knockoutjs官方文件

沒有留言:

張貼留言