日期:2014-05-16 浏览次数:20441 次
// 创建一个简单的viewmodel
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
// 动态属性
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
// computed properties 计算属性
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
// last name变大写函数(行为)
this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
// data-bind属性是Knockout 用来显示关联UI和viewmodel的桥梁 text 表示把绑定的文本赋值给DOM元素 <!-- This is a *view* - HTML markup that defines the appearance of your UI --> // 静态文本绑定 <p>First name: <strong data-bind="text: firstName">todo</strong></p> <p>Last name: <strong data-bind="text: lastName">todo</strong></p> // 使用data-bind="value: firstName"来动态绑定到input 输入框的值 当文本框的值发生变化时,ko先更新viewmodel的数据,然后根据observables,来更新Label的值 <p>First name: <input data-bind="value: firstName" /></p> <p>Last name: <input data-bind="value: lastName" /></p> <p>Full name: <strong data-bind="text: fullName"></strong></p> <button data-bind="click: capitalizeLastName">Go caps</button>