日期:2014-05-16 浏览次数:20396 次
// 动态绑定(主动订阅,取消订阅) var subscription = myViewModel.personName.subscribe(function(newValue) { /* do stuff */ }); // ...then later... subscription.dispose(); // I no longer want notifications // Computed Observables this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); var myObservableArray = ko.observableArray(); // Initially an empty array myObservableArray.push('Some value'); // Adds the value and notifies observers // 初始化绑定数组 // This observable array initially contains three objects var anotherObservableArray = ko.observableArray([ { name: "Bungle", type: "Bear" }, { name: "George", type: "Hippo" }, { name: "Zippy", type: "Unknown" } ]); // 自定义排序 myObservableArray.sort(function(left, right) { return left.lastName == right.lastName ? 0 : (left.lastName < right.lastName ? -1 : 1) }) // 可写的依赖属性 --- 数字自动格式化显示,保存值时移除无关逗号 function MyViewModel() { this.price = ko.observable(25.99); this.formattedPrice = ko.computed({ read: function () { return '$' + this.price().toFixed(2); }, write: function (value) { // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable value = parseFloat(value.replace(/[^\.\d]/g, "")); this.price(isNaN(value) ? 0 : value); // Write to underlying storage }, owner: this }); } ko.applyBindings(new MyViewModel());