ko练习(1)

可写的依赖监控属性(双向数据绑定)

firstName:

lastName:

fullName:

var ViewModel = function(){ var self = this; this.firstName = ko.observable('Britney'); this.lastName = ko.observable('Spears'); this.fullName = ko.dependentObservable({ read:function(){ return this.firstName()+" "+this.lastName(); }, write:function(value){ var lastSpacePos = value.lastIndexOf(" "); if(lastSpacePos > 0){ this.firstName(value.substring(0,lastSpacePos)); this.lastName(value.substring(lastSpacePos+1)); } }, owner:self //ko调用read,write 的callback时用到的this,即read,write的callback中的this指向self }); }; var myViewModel = new ViewModel(); ko.applyBindings(myViewModel);

监控数组(observableArray)

//声明监控数组
var myObservableArray = ko.sbservableArray();

//向监控数组中添加数据
myObservableArray().push({name:'zhangsan'},age:20);


//声明的时候初始化数据
var myObservableArray = ko.observableArray([
    {name:'zhangsan',age:18},
    {name:'lisi',age:13},
    {name:'wangwu',age:21},
    {name:'zhaoliu',age:23},
]);    

//读取监控数组的数据
alert(myObservableArray().length);
alert(myObservableArray()[0].name);

//ko提供的读取方法

1.indexOf()

2.slice()//等价与JS原生slice方法,返回给定的开始索引到结束索引之间的所有对象集合
      var arr = myObservableArray().slice(1,myObservableArray().length);
      alert(arr.length);//[{name:'lisi',age:13}, {name:'wangwu',age:21}, {name:'zhaoliu',age:23}]

3.  myObservableArray.push({name:'朱元璋',age:(2016-1328)}) //在数组末尾添加一个新项
    myObservableArray.pop() //删除数组最后一个项并返回该项
    myObservableArray.unshift({name:'太祖',age:(2016-1893)}) //在数组头部添加一个项
    var firstItem = myObservableArray.shift() //删除数组头部第一项并返回该项
    myObservableArray.reverse() //翻转整个数组的顺序
    myObservableArray.sort() //给数组排序

你可能感兴趣的:(ko练习(1))