Knockout Custom binding creation method _javascript tips

Source: Internet
Author: User
Tags visibility

Overview

You can also create custom bindings in addition to the KO built-in binding type (such as value, text, and so on) that is listed in the previous article.

Sign up for your binding handler

Ko.bindingHandlers.yourBindingName = {
  init:function (element, Valueaccessor, allbindings, ViewModel, BindingContext) {//This'll be called when the binding is a-a-a
    element
    //Set up any initial STA Te, event handlers, etc. here
  },
  update:function (element, Valueaccessor, allbindings, ViewModel, BindingContext) {
    //This'll be called once then the binding is a-a element,
    //and applied again Er any observables/computeds this are accessed change
    //Update The DOM element based on the supplied values Here.
   }

Next you can use a custom binding on any DOM element:

 
 

Note: You do not have to provide both INIT and update callback in your handler to provide any one.

Update callback

As the name suggests, KO will automatically call your update callback when your monitoring properties are observable updated.

It has the following parameters:

element: A DOM element that uses this binding;

Valueaccessor: The Model property value of the current binding can be obtained by calling Valueaccessor (), and invoking Ko.unwrap (Valueaccessor ()) makes it easier to obtain observable values and normal values;

Allbindings: All property values that are bound to model on this DOM element, such as calling Callbindings.get (' name ') to return the binding's Name property value (no return undefined exists). or call Allbindings.has (' name ') to determine if name is bound to the current DOM;

ViewModel: Discard in knockout.3x, available bindingcontext. $data or BindingContext. $rawData to get the current ViewModel;

BindingContext: Binding context that can call BindingContext. $data, BindingContext. $parent, BindingContext. $parents, etc. to obtain data;

Next, for example, you might want to use the visible binding to control the visibility of the element and animate it, at which point you can create your own custom binding:

ko.bindingHandlers.slideVisible = {
  update:function (element, Valueaccessor, allbindings) {
    //the The Latest data that we ' re bound to
    var value = Valueaccessor ();
    Next, whether or not the supplied model property is observable, get its value
    var valueunwrapped = Ko.unwra P (value);
    Grab some more data from another binding property
    var duration = allbindings.get (' slideduration ') | |//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 can then use this custom binding:

<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);

Init callback

Ko will call your init function for each DOM element that uses the binding, which has two main uses:

(1) Setting the initialization state for the DOM element;

(2) Register some event handlers, for example: when the user clicks or modifies the DOM element, you can change the state of the monitoring attribute;

Ko will use exactly the same set of parameters as the update callback.

To continue with the previous example, you may want slidevisible to set the visibility state of the element (without any animation) when the page first appears, and the animation effect is performed at a later time, and you can do it in the following way:

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 would hide/show the Element depending on whether "value" or True or false
  },
  update:function (element, Valueaccessor, allbindings) { c6/>//Leave as before
  }

Giftwrap is initialized to False (Ko.observable (false)), the associated Div is hidden when it is initialized, and then the user clicks on the checkbox for the div to appear.

You now know how to use the update callback, and you can update the DOM elements when the observable value changes. We can now do it in a different way, such as when the user has an action action that can also cause your observable value to be updated, for example:

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 ();
  }

Now you can read and write your observable value by the element's "focusedness" binding.

<p>name: <input data-bind= "Hasfocus:editingname"/></p>
<!--showing that we can both read and W Rite 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>

The above content is small make up to share knockout custom binding creation method, hope everybody likes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.