
ko.bindingHandlers是先执行init进行初始化数据的绑定(如果需要执行updata进行数据更新可以不用初始化);
init: function(element, valueAccessor) {
//初始化数据--然后执行updata进行需要更新数据的绑定,添加订阅
//如果在updata进行了数据的执行,init可以添加初始化事件
var value = valueAccessor(); // Get the current value of the current property we're bound to
$(element).text(value); // jQuery will hide/show the element depending on whether "value" or true or false
},
ko.bindinHandlers.init
在updata里面,才是订阅产生的时候,而不是在init的时候,数据就绑定了订阅;
update: function(element, valueAccessor, allBindings) {
var value = ko.unwrap(valueAccessor()); //执行更新数据绑定,必须要执行一次否则无法确定添加订阅
//var value = valueAccessor()(); // Get the current value of the current property we're bound to
$(element).text(value);
}
ko.dindingHandlers.updata
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="js/knockout-3.4.0.debug.js"></script>
<script type="text/javascript">
ko.bindingHandlers.slideVisible = {
init: function(element, valueAccessor) {
//初始化数据--然后执行updata进行需要更新数据的绑定,添加订阅
//如果在updata进行了数据的执行,init可以添加初始化事件
var value = valueAccessor(); // Get the current value of the current property we're bound to
$(element).text(value); // jQuery will hide/show the element depending on whether "value" or true or false
},
update: function(element, valueAccessor, allBindings) {
var value = ko.unwrap(valueAccessor()); //执行更新数据绑定,必须要执行一次否则无法确定添加订阅
//var value = valueAccessor()(); // Get the current value of the current property we're bound to
$(element).text(value);
}
};
var model = {
te: ko.observable("ttttttttt"),
aaa: function() {
this.te("aaaaaaaaaaaaaaaaaaaa");
}
}
window.onload = function() {
ko.applyBindings(model, document.body)
}
</script>
</head> <body>
<div data-bind="slideVisible:te"></div>
<input type="button" value="aaaaaaaaa" data-bind="click:aaa" />
</body>
</html>
ko.bindingHandlers.model
注:小七目前还是小白,写的博客为笔记类型的博客,是在项目中遇到的问题,仅用于学习。
涉及到原理部分还未做总结。
如果内容有不对、不全面或者其他的问题,欢迎大家纠正。