參考: http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html http://knockoutjs.com/documentation/introduction.html 複習:AngularJS的數據綁定 顯示文本 <p>{{gre
參考:
http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html
http://knockoutjs.com/documentation/introduction.html
複習:AngularJS的數據綁定
顯示文本
<p>{{greeting}}</p>
或者
<p ng-bind=”greeting”></p>
表單輸入
<form ng-controller=”SomeController”>
<input type=”checkbox” ng-model=”youCheckedIt”>
</form>
列表
<ul ng-controller=’StudentController’>
<li ng-repeat=’student in students’>
<a href=’/student/view/{{student.id}}’>{{student.name}}</a>
</li>
</ul>
表格
<table ng-controller=’AlbumController’>
<tr ng-repeat=’track in album’>
<td>{{$index+1}}</td>
<td>{{track.name}}</td>
<td>{{track.duration}}</td>
</tr>
</table>
使用$watch監控數據模型的變化
Knockout基礎學習
示例代碼出現錯誤,提示jquery-tmpl版本太舊,解決辦法
http://blog.degree.no/2012/09/microsoft-jscript-error-jquery-tmpl-is-too-old/
庫的線上引用地址
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="./jquery.tmpl.js"></script>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-latest.js"></script>
Jquery.tmpl.js下載自
https://raw.githubusercontent.com/BorisMoore/jquery-tmpl/master/jquery.tmpl.js
https://github.com/BorisMoore/jquery-tmpl
入門
重要概念:
聲明式綁定
UI界面自動刷新
依賴跟蹤
模板
基本使用
啟用綁定
ko.applyBindings(viewModel)
數據模型
var viewModel = {
chosenMeal: ko.observable(availableMeals[0])
}
數據
var availableMeals = [
{ mealName: 'Standard', description: 'Dry crusts of bread', extraCost: 0 },
{ mealName: 'Premium', description: 'Fresh bread with cheese', extraCost: 9.95 },
{ mealName: 'Deluxe', description: 'Caviar and vintage Dr Pepper', extraCost: 18.50 }
];
使用綁定,寫變數
Chosen meal: <select data-bind="options: availableMeals,
optionsText: 'mealName',
value: chosenMeal"></select>
使用綁定,讀變數,並作為參數提供給函數
<p>
You've chosen:
<b data-bind="text: chosenMeal().description"></b>
(price: <span data-bind='text: formatPrice(chosenMeal().extraCost)'></span>)
</p>
格式化函數
function formatPrice(price) {
return price == 0 ? "Free" : "$" + price.toFixed(2);
}
Observables 可觀察變數
概念
observables, Dependent Observables, Observable Array
核心功能
observables 可觀察變數 Dependency tracking 依賴跟蹤
declarative bindings 顯式綁定
templating 模板
View-Model
視圖模型
激活Knockout
ko.applyBindings(myViewModel, document.getElementById('someElementId'))
可觀察變數,聲明
var myViewModel = {
personName: ko.observable('Bob'),
personAge: ko.observable(123)
};
可觀察變數,讀寫
讀:myViewModel.personAge()
寫:myViewModel.personName('Mary'),支持鏈式語法
綁定,data-bind,註冊到可觀察變數
可觀察變數,顯示訂閱
var subscription = myViewModel.personName.subscribe(function (newValue) { /* do stuff */ });
// ...then later...
subscription.dispose(); // I no longer want notifications
依賴可觀察變數
var viewModel = {
firstName: ko.observable('Bob'),
lastName: ko.observable('Smith')
};
viewModel.fullName = ko.dependentObservable(function () {
return this.firstName() + " " + this.lastName();
}, viewModel);
從依賴變數寫入可觀察變數
viewModel.fullName = ko.dependentObservable({
read: function () {
return this.firstName() + " " + this.lastName();
},
write: function (value) {
var lastSpacePos = value.lastIndexOf(" ");
if (lastSpacePos > 0) { // Ignore values with no space character
this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
}
},
owner: viewModel
});
使用依賴變數數組observable array
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" }
]);
js等價讀取信息:length, indexOf, slice
js數組等價操作:pop, push, shift, unshift, reverse, sort, splice
特殊操作:remove, removeAll
綁定語法一
visible: 綁定到DOM元素,控制元素是否顯示
text: 控制元素的文本值
html: 控制元素顯示的HTML值
css: 添加或刪除一個或多個CSS class到DOM元素上
style: 添加或刪除一個或多個DOM元素上的style值
attr: 提供了一種方式可以設置DOM元素的任何屬性值
綁定語法二
click
event, 例如keypress, mouseover, mouseout
submit
enable
disable
綁定語法三
value, <input>, <select>, <textarea>
checked, <input type=’checkbox’>, <input type=’radio’>
options, <select>, <select size=’6’>
selectedOptions, multi-select
uniqueName
模板綁定
jquery.tmpl
你可以使用任何你模板引擎支持的語法。jquery.tmpl執行如下語法:
${ someValue } — 參考文檔
{{html someValue}} — 參考文檔
{{if someCondition}} — 參考文檔
{{else someCondition}} — 參考文檔
{{each someArray}} — 參考文檔
創建自定義綁定
ko.bindingHandlers.yourBindingName = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
}
};
載入或保存JSON數據
載入或保存數據:例如使用jQuery的$.getJSON, $.post, $.ajax
轉化ViewModel數據到JSON格式,有時需要json2.js類庫
ko.toJS 轉化為JS對象
ko.toJSON 轉化為JSON字元串
使用JSON更新ViewModel數據
手動方式
或者使用 knockout.mapping
使用Mapping插件
var viewModel = ko.mapping.fromJS(data); //創建ViewModel
ko.mapping.fromJS(data, viewModel); //更新ViewModel
用法:
key, create, update, ignore, include, copy
兩種方式創建viewModel
應用舉例
常用的控制項