这篇文章给大家介绍Knockout应用开发中如何创建自定义绑定,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联公司作为成都网站建设公司,专注重庆网站建设公司、网站设计,有关成都定制网站方案、改版、费用等问题,行业涉及隧道混凝土搅拌车等多个领域,已为上千家企业服务,得到了客户的尊重与认可。
创建自定义绑定
你可以创建自己的自定义绑定,没有必要非要使用内嵌的绑定(像click,value等)。你可以你封装复杂的逻辑或行为,自定义很容易使用和重用的绑定。例如,你可以在form表单里自定义像grid,tabset等这样的绑定。
重要:以下文档只应用在Knockout 1.1.1和更高版本,Knockout 1.1.0和以前的版本在注册API上是不同的。
注册你的绑定
添加子属性到ko.bindingHandlers来注册你的绑定:
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. } };
然后就可以在任何DOM元素上使用了:
注:你实际上没必要把init和update这两个callbacks都定义,你可以只定义其中的任意一个。
update 回调
当管理的observable改变的时候,KO会调用你的update callback函数,然后传递以下参数:
◆ element — 使用这个绑定的DOM元素
◆ valueAccessor —JavaScript函数,通过valueAccessor()可以得到应用到这个绑定的model上的当前属性值。
◆ allBindingsAccessor —JavaScript函数,通过allBindingsAccessor ()得到这个元素上所有model的属性值。
◆ viewModel — 传递给ko.applyBindings使用的 view model参数,如果是模板内部的话,那这个参数就是传递给该模板的数据。
例如,你可能想通过 visible绑定来控制一个元素的可见性,但是你想让该元素在隐藏或者显示的时候加入动画效果。那你可以自定义自己的绑定来调用jQuery的slideUp/slideDown 函数:
ko.bindingHandlers.slideVisible = { update: function(element, valueAccessor, allBindingsAccessor) { // First get the latest data that we're bound to var value = valueAccessor(), allBindings = allBindingsAccessor(); // Next, whether or not the supplied model property is observable, get its current value var valueUnwrapped = ko.utils.unwrapObservable(value); // Grab some more data from another binding property var duration = allBindings.slideDuration || 400; // 400ms is default duration unless otherwise specified // Now manipulate the DOM element if (valueUnwrapped == true) $(element).slideDown(duration); // Make the element visible else $(element).slideUp(duration); // Make the element invisible } };
然后你可以像这样使用你的绑定:
You have selected the option