打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
KnockoutJS学习笔记24:KonckoutJS customBinding自定义绑定

KnockoutJS 自定义绑定(Custom Binding)允许我们通过代码实现自定义绑定规则,从而完成更高级的业务需求。

示例代码

ko.bindingHandlers.yourBindingName = {    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {        // 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, allBindings, viewModel, bindingContext) {        // This will be called once when the binding is first applied to an element,        // and again whenever any observables/computeds that are accessed change        // Update the DOM element based on the supplied values here.    }};

在自定义绑定的方法中,我们需要向ko.bindingHandlers中添加一个绑定的名称,然后在里面实现init和update方法。从代码结构上来看,实现自定义绑定(custom Binding)并不复杂。下面我们来看一下init和update方法:

init:初始化方法,在DOM绑定时候被调用一次,并且只被调用一次。init方法有两个常用的场景

  • 为DOM设置初始化状态
  • 注册一些事件。例如我们需要在input改变的时候来同步数据到ko的ViewModel中,这个时候就需要在init的时候注册事件。

如果没有这些需要初始化一次的要求,那么init方法是不需要定义的(在init方法执行完成之后,ko会使用相同的参数调用update方法)。

update:update方法会在init方法执行完成之后执行,并且在监视属性或其他依赖属性(observables/computeds)发生改变的时候被调用来更新界面。update方法更常用一些。

下面是一个完整的例子:

ko.bindingHandlers.slideVisible = {    update: function (element, valueAccessor, allBindings) {        // First get the latest data that we're bound to        var value = valueAccessor();        // Next, whether or not the supplied model property is observable, get its current value        var valueUnwrapped = ko.unwrap(value);        // Grab some more data from another binding property        var duration = allBindings.get('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    }};

对应的用法:

<div data-bind="slideVisible: giftWrap, slideDuration: 600">You have selected the option</div><label><input type="checkbox" data-bind="checked: giftWrap" /> Gift wrap</label> <script type="text/javascript">    var viewModel = {        giftWrap: ko.observable(true)    };    ko.applyBindings(viewModel);</script>

如何支持虚拟节点?

ko的if、foreach等绑定支持虚拟节点,那么我们如何让自己的代码来支持虚拟节点呢?

首先,我们自定义一个绑定:

ko.bindingHandlers.randomOrder = {    init: function (elem, valueAccessor) {        // Pull out each of the child elements into an array        var childElems = [];        while (elem.firstChild)            childElems.push(elem.removeChild(elem.firstChild));        // Put them back in a random order        while (childElems.length) {            var randomIndex = Math.floor(Math.random() * childElems.length),                chosenChild = childElems.splice(randomIndex, 1);            elem.appendChild(chosenChild[0]);        }    }};

在DOM节点中的用法:

<div data-bind="randomOrder: true">    <div>First</div>    <div>Second</div>    <div>Third</div></div>

如果我们想要在虚拟节点中使用,例如:

<!-- ko randomOrder: true -->    <div>First</div>    <div>Second</div>    <div>Third</div><!-- /ko -->

那么,我们需要在KO中注册,允许我们的自定义绑定用在虚拟节点中:

ko.virtualElements.allowedBindings.randomOrder = true;

接下来对我们的自定义绑定进行修改:

ko.bindingHandlers.randomOrder = {    init: function (elem, valueAccessor) {        // Build an array of child elements        var child = ko.virtualElements.firstChild(elem),            childElems = [];        while (child) {            childElems.push(child);            child = ko.virtualElements.nextSibling(child);        }        // Remove them all, then put them back in a random order        ko.virtualElements.emptyNode(elem);        while (childElems.length) {            var randomIndex = Math.floor(Math.random() * childElems.length),                chosenChild = childElems.splice(randomIndex, 1);            ko.virtualElements.prepend(elem, chosenChild[0]);        }    }};

这样一来我们自定义的绑定就能用在虚拟节点中了。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
翻译:Knockout 快速上手 - 5: 你需要知道的顶级特性 续
前端开发框架Bootstrap和KnockoutJS
jQuery源码解析1(Utilities)
使用jquery封装的动画脚本(无动画、css3动画、js动画)
jquery滑动效果的运动模块封装
显示层封装及实现与优化(无动画+css3动画+js动画)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服