显示视图模型对象的属性时,往往需要设置一定的格式,或者显示的值依赖于对象的属性,这时,需要定义依赖属性。依赖属性实际上是一个函数,比如下面的例子,根据身高和体重计算BMI:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="Lib/Kendo/css/kendo.common-bootstrap.min.css">
<link rel="stylesheet" href="Lib/Kendo/css/kendo.bootstrap.min.css">
<script src="Scripts/jquery-3.3.1.min.js"></script>
<!--jquery 兼容性-->
<script src="Scripts/jquery-migrate-3.0.1.min.js"></script>
<script src="Lib/Kendo/js/kendo.all.min.js"></script>
<!--本地化-->
<script src="Lib/Kendo/js/kendo.messages.zh-CN.min.js"></script>
<script src="Lib/Kendo/js/kendo.culture.zh-CN.min.js"></script>
</head>
<body>
<div id="view">
体重:<input data-bind="value: weight" /><br/>
身高:<input data-bind="value:height" /><br/>
BMI:<span data-bind="text:bmi"></span>
</div>
<script>
$(document).ready(function () {
var viewModel = kendo.observable({
height: 1.76,
weight: 75,
bmi: function () {
return this.get("weight") / this.get("height") / this.get("height");
}
});
kendo.bind($("#view"), viewModel);
});
</script>
</body>
</html>
也可以通过设置参数,设置属性值,例子如下:
<p>Full Name: <input data-bind="value: fullName"></p>
<p>First Name: <span data-bind="text: firstName"></span></p>
<p>Last Name: <span data-bind="text: lastName"></span></p>
<script>
var vm = kendo.observable({
firstName: "John",
lastName: "Doe",
fullName: function(value) {
if (value !== undefined) {
var name = value.split(" ");
this.set("firstName", name[0]);
this.set("lastName", name[1]);
} else {
return this.get("firstName") + " " + this.get("lastName");
}
}
});
kendo.bind(document.body, vm);
</script>
需要注意,如果需要操作视图模型对象,一定要在视图模型对象初始化之后进行。