Knockout自定义绑定创建方法

概述

除了上一篇列出的KO内置的绑定类型(如value、text等),你也可以创建自定义绑定。

注册你的binding handler

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.
  }
}; 

接下来你就可以在任意dom元素上使用的自定义绑定了:

<div data-bind="yourBindingName: someValue"> </div> 

注意:你不必在你的handler里把init和update的callback都提供,可以提供任意一个。

update callback

顾名思义,当你的监控属性observable更新的时候,ko会自动调用你的update回调。

它有以下参数:

    element:使用这个绑定的dom元素;

    valueAccessor  : 通过调用valueAccessor()可以获得当前绑定的model属性值,调用ko.unwrap(valueAccessor())能够更方便的获取observable的值和普通值;

    allBindings : 绑定到这个dom元素上的model的所有属性值,例如调用callBindings.get('name') 返回绑定的name属性值(不存在返回undefined),或者调用allBindings.has('name')判断name是否绑定到了当前的dom中;

    viewModel  : 在Knockout.3x中以弃用,可用bindingContext.$data或者bindingContext.$rawData来获取当前的viewModel;

   bindingContext  : 绑定上下文,可调用bindingContext.$data、 bindingContext.$parent, bindingContext.$parents等获取数据;

接下来看一个例子,你也许希望使用visible绑定来控制元素的可见性,并且加上动画效果,这时你可以创建你的自定义绑定:

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> 

init callback

ko将为每个使用绑定的dom元素调用你的init函数,它有两个主要用途:

(1)为dom元素设置初始化状态;

(2)注册一些事件处理程序,例如:当用户点击或者修改dom元素时,你可以改变监控属性的状态;

ko将使用和update回调完全相同一组参数。

继续前面的例子,你也许想让slideVisible在页面第一次显示的时候就设置该元素的可见性状态(没有任何动画效果),而动画效果是在以后改变的时候执行,你可以按照下面的方式来做:

ko.bindingHandlers.slideVisible = {
  init: function(element, valueAccessor) {
    var value = ko.unwrap(valueAccessor()); // Get the current value of the current property we're bound to
    $(element).toggle(value); // jQuery will hide/show the element depending on whether "value" or true or false
  },
  update: function(element, valueAccessor, allBindings) {
    // Leave as before
  }
}; 

giftWrap被初始化定义为false(ko.observable(false)),关联的DIV会在初始化的时候隐藏,之后用户点击checkbox时才让DIV显示。

你现在已经知道如何使用update回调了,当observable值改变的时候你可以更新dom元素。我们现在可以用另外的方法来做,比如当用户有某个action操作时,也能引起你的observable值更新,例如:

ko.bindingHandlers.hasFocus = {
  init: function(element, valueAccessor) {
    $(element).focus(function() {
      var value = valueAccessor();
      value(true);
    });
    $(element).blur(function() {
      var value = valueAccessor();
      value(false);
    });
  },
  update: function(element, valueAccessor) {
    var value = valueAccessor();
    if (ko.unwrap(value))
      element.focus();
    else
      element.blur();
  }
}; 

现在你可以通过元素的“focusedness”绑定来读写你的observable值了。

<p>Name: <input data-bind="hasFocus: editingName" /></p>
<!-- Showing that we can both read and write the focus state -->
<div data-bind="visible: editingName">You're editing the name</div>
<button data-bind="enable: !editingName(), click:function() { editingName(true) }">Edit name</button>
<script type="text/javascript">
  var viewModel = {
    editingName: ko.observable()
  };
  ko.applyBindings(viewModel);
</script>

以上内容是小编给大家分享的Knockout自定义绑定创建方法,希望大家喜欢。

若文章对您有帮助,帮忙点个赞!

0
-3
发布时间 2015-12-26 11:45:56
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)