data-bind="text: firstName"中data-bind属性是Knockout 用来显示关联UI和viewmodel的桥梁, text 表示把绑定的文本赋值给DOM元素 click 用来关联按钮点击事件 data-bind="value: firstName"来动态绑定到input 输入框的值 当文本框的值发生变化时,ko先更新viewmodel的数据,然后根据observables,来更新Label的值。valueUpdate: "afterkeydown"'可以控制什么事件才触发value的更新操作, 默认onchange observables: 观察者模式,当属性发生变化时,主动通知相关者 computed properties: 根据基础属性计算得到新的属性,当基础属性发生变化时,ko会自动重新计算新的值
- // 创建一个简单的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>