简单示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<!-- <span data-bind="text: personName"></span> -->
<h3>Meal upgrades</h3>
<p>Make your flight more bearable by selecting a meal to match your social and economic status.</p>
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: chosenMeal().extraCost'></span>)
<br>
<!-- formatPrice方法 -->
(price: <span data-bind='text: formatPrice(chosenMeal().extraCost)'></span>)
</p>
</body>
<script type="text/javascript" src="../knockout-3.5.0rc2.debug.js"></script>
<script type="text/javascript">
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 },
];
var viewModel = {
chosenMeal: ko.observable(availableMeals[0]) //ko.observable:UI可以监控(observe)
};
ko.applyBindings(viewModel); // 注意:ko. applyBindings需要在上述HTML之后应用才有效
function formatPrice(price) {
return price == 0 ? "Free" : "$" + price.toFixed(2);
}
</script>
</html>
监控属性(Observables)
demo2-1.observable.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<!-- text绑定注册到自身 -->
The name is <span data-bind="text: personName"></span>
<br />The Age is
<span data-bind="text: personAge"></span>
</body>
<script src="../knockout-3.5.0rc2.debug.js"></script>
<script>
var myViewModel = {
personName: "Bob1",
personAge: 123
};
myViewModel = {
personName: ko.observable("Bob2"),
personAge: ko.observable(123)
};
ko.applyBindings(myViewModel);
myViewModel.personName("Mary").personAge(111);
</script>
</html>
demo2-2.fullname.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<!-- text 绑定注册到自身 -->
The name is <span data-bind="text: fullName"></span>
</body>
<script src="../knockout-3.5.0rc2.debug.js"></script>
<script>
var viewModel = {
firstName: ko.observable("Bob"),
lastName: ko.observable("Smith")
};
// 依赖监控属性(Dependent Observables)
// 这些函数是一个或多个监控属性, 如果他们的依赖对象改变,他们会自动跟着改变。
//computed == dependentObservable
viewModel.fullName = ko.dependentObservable(function() {
return this.firstName() + " " + this.lastName();
}, viewModel);
ko.applyBindings(viewModel);
</script>
</html>
The name is Bob Smith
转自:http://Www.CnBlogs.Com/WebEnh/
如果想下次快速找到我,记得点下面的关注哦!
本博客Android APP 下载 |
![]() |
支持我们就给我们点打赏 |
![]() |
支付宝打赏 支付宝扫一扫二维码 |
![]() |
微信打赏 微信扫一扫二维码 |
![]() |
如果想下次快速找到我,记得点下面的关注哦!