Knockout的监控链一个小例子

普通数组,与Knockout数组关联,Knockout数组与select元素关联。

于是,你用Knockout内置函数,处理了Knockout数组,普通数组也随着改变,select元素随着改变。

你改变了select元素,Knockout数组随着改变,普通数组随着改变。

你通过内置函数改变了普通数组,Knockout数组改变, select元素改变。

这就是MVVM,普通数组是Model,Knockout数组是View-Model,select元素是View。

 

但是,你重新绑定了,就另当别论了。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="knockout-2.0.0.debug.js"></script>
<script type="text/javascript">
$(
function(){
    
    
var testKo=function(){
        
this.testArray=["1","2","3","4","5"];
        
this.koArray =ko.observableArray([]);
        
this.koArray(this.testArray);
        console.log(
"knockout array is "+this.koArray());
        
this.koArray(["6","7"]);//rebind
        console.log("normal array is "+this.testArray);//origin nomral array
        this.testArray.push("8");
        console.log(
"knockout array is " + this.testArray);

        
this.testArray = ["44"];
        console.log(
"kockout array is "+this.koArray());
        
this.testArray.push("55");
        console.log(
"knockout array is " + this.koArray());

        
//restart
        this.newArray = ["aa","bb","cc"];
        
this.newKoArray = ko.observableArray(this.newArray);
        console.log(
this.newKoArray());
        
this.newArray.push("dd");
        console.log(
this.newKoArray());
        
this.newKoArray.remove("aa");
        console.log(
this.newArray);

    }
    ko.applyBindings(
new testKo());
})
;
</script>
</head>

<body>

</body>
</html>
posted @ 2012-04-17 15:45  草珊瑚  阅读(1309)  评论(4编辑  收藏  举报