- 加入偵聽
var mysubscription = myViewModel.userName.subscribe(function(newValue){
//屬性變動時要做的處理
}); - 移除屬性偵聽
mysubscription.dispose();
<!DOCTYPE html>
<html>
<head>
<title>屬性變動偵聽與移除</title>
<meta charset="UTF-8"/>
<script src="../lib/jquery-1.7.1.min.js"></script>
<script src="../lib/knockout-2.1.0.js"></script>
<script>
$(window).ready(function (){
var companysInfo = [
{name:"Apple",twName:"蘋果"} ,
{name:"HTC",twName:"宏達電"} ,
{name:"Samsung",twName:"三星"}];
var defaultName = companysInfo[0].twName;
$('#enName').html(companysInfo[0].name);
var myViewModel = {
userName : ko.observable(defaultName),
companys:ko.observableArray(companysInfo)
};
//加上偵聽
var mysubscription = myViewModel.userName.subscribe(function(newValue) {
for(var i in myViewModel.companys()){
//如果比較相同,就將英文名稱換掉
(myViewModel.companys()[i].twName == newValue
&& $('#enName').html(myViewModel.companys()[i].name));
}
});
//設定ko綁定
ko.applyBindings(myViewModel);
//select changed
$('#companys').change(function(){
myViewModel.userName(myViewModel.companys()[this.value].twName);
});
//移除屬性變動偵聽
$('#btn').click(function(){
mysubscription.dispose();
});
});
</script>
</head>
<body>
中文:<span data-bind="text:userName"></span></br>
英文:<span id="enName"></span>
<div>
<select id="companys" data-bind="foreach:companys">
<option data-bind="text:name , value:$index"></option>
</select>
</div>
<input id="btn" type="button" value="移除屬性變動偵聽" />
</body>
</html>
<html>
<head>
<title>屬性變動偵聽與移除</title>
<meta charset="UTF-8"/>
<script src="../lib/jquery-1.7.1.min.js"></script>
<script src="../lib/knockout-2.1.0.js"></script>
<script>
$(window).ready(function (){
var companysInfo = [
{name:"Apple",twName:"蘋果"} ,
{name:"HTC",twName:"宏達電"} ,
{name:"Samsung",twName:"三星"}];
var defaultName = companysInfo[0].twName;
$('#enName').html(companysInfo[0].name);
var myViewModel = {
userName : ko.observable(defaultName),
companys:ko.observableArray(companysInfo)
};
//加上偵聽
var mysubscription = myViewModel.userName.subscribe(function(newValue) {
for(var i in myViewModel.companys()){
//如果比較相同,就將英文名稱換掉
(myViewModel.companys()[i].twName == newValue
&& $('#enName').html(myViewModel.companys()[i].name));
}
});
//設定ko綁定
ko.applyBindings(myViewModel);
//select changed
$('#companys').change(function(){
myViewModel.userName(myViewModel.companys()[this.value].twName);
});
//移除屬性變動偵聽
$('#btn').click(function(){
mysubscription.dispose();
});
});
</script>
</head>
<body>
中文:<span data-bind="text:userName"></span></br>
英文:<span id="enName"></span>
<div>
<select id="companys" data-bind="foreach:companys">
<option data-bind="text:name , value:$index"></option>
</select>
</div>
<input id="btn" type="button" value="移除屬性變動偵聽" />
</body>
</html>