Knockoutjs 3.X API Fifth Advanced Applications (5) Using preprocessing extensions knockout binding syntax

Source: Internet
Author: User

Note: This is an advanced technique that is typically used only when creating reusable libraries for binding or extended syntax. This is not something you usually need to do when building an application using knockout.

Starting with knockout 3.0, developers can define custom syntax by providing callbacks that rewrite DOM nodes and binding strings during the binding process.

Preprocessing binding strings

You can hook knockout logic to interpret data-binding properties by providing a binding preprocessor for a specific binding handler, such as click,visible or any custom binding handler.

To do this, attach a preprocessing function to the binding handler:

function (stringfrommarkup) {    //  Return stringfrommarkup If you don't want to change anything, or return< /c4>    //  Some other string if your want Knockout to behave as ifthat is the    //  SYN Tax provided in the original HTML}

See the API reference later in this page for specific parameters.

Example 1: Set default values for bindings

If you discard a bound value, its default binding is undefined. If you want to have a different default value for the binding, you can use a preprocessor. For example, you can allow a value to be bound without a value by setting the default value of UniqueName to true:

function (val) {    return val | | ' True ';}

Now you can bind like this:

<data-bind= "Value:somemodelproperty, uniqueName"/>
Example 2: Binding an expression to an event

If you want to be able to bind an expression to a click event (rather than knockout the expected function reference), you can set the preprocessor to support this syntax for the click handler:

function (val) {    return ' function ($data, $event) {' + val + '} ';}

Now you can bind the click:

<type= "button"  data-bind= "Click:mycount (MyCount () +1)" > Increment</button>
Binding Preprocessor Reference

ko.bindingHandlers.<name>.preprocess(value, name, addBindingCallback)

If defined, this function is called for each <name> binding before the binding is evaluated.

Parameters:

    • value: Knockout the syntax before attempting to parse the bound value (for example, for Binding:1 + 1, the association value is "1 + 1" as a string).

    • name: The name of the binding (for example, for your Binding:1 + 1, the name is "Yourbinding" as a string).

    • addBinding: A callback function that you can choose to use to insert another binding on the current element. This requires two parameters, a name and a value. For example, in your preprocessing function, call addbinding (' visible ', ' acceptsterms () '); Makes knockout behave as if there is a visible:acceptsterms () binding on the element.

return value :

Your preprocessing function must return a new string value to parse and pass to the binding, or return undefined to remove the binding.
For example, if you return ' value + '. toUpperCase () "' as a string, then your binding:" Bert "will be interpreted as a token containing your binding:" Bert ". toUpperCase (). Knockout will parse the returned value in the normal way, so it must be a legitimate JavaScript expression.
Non-string values are not returned. This doesn't make sense because the tag is always a string. Preprocessing DOM nodes

You can traverse the DOM by providing a node preprocessor to hook into the knockout logic. This is a function that knockout will call once for each DOM node it traverses, whether it is the first time the UI is bound or when any new DOM subtree is injected (for example, through a foreach binding).

To do this, define the Preprocessnode function on the binding provider:

Ko.bindingProvider.instance.preprocessNode =function(node) {//Use the DOM APIs such as setAttribute to modify ' node ' if you wish.    //If you want to leave ' node ' in the DOM, return null or has no ' return ' statement.    //If you want-to-replace ' node ' with some and other set of nodes,    //-use DOM APIs such as Insertchild to inject the new nodes    //immediately before ' node '    //-use DOM APIs such as removechild to remove ' node ' if required    //-Return An array of any new nodes so you ' ve just inserted    //So, Knockout can apply any bindings to them}

Example 3: Virtual template element

If you typically use virtual elements to contain template content, the normal syntax can feel a bit verbose. With preprocessing, you can add a new template format that uses a single comment:

Ko.bindingProvider.instance.preprocessNode =function(node) {//Only react If this is a comment node of the form <!--Template: ... -    if(Node.nodetype = = 8) {        varMatch = Node.nodeValue.match (/^\s* (template\s*:[\s\s]+)/); if(match) {//Create A pair of comments to replace the single comment            varC1 = document.createcomment ("ko" + match[1]), C2= Document.createcomment ("/ko");            Node.parentNode.insertBefore (c1, node);             Node.parentNode.replaceChild (c2, node); //Tell Knockout on the new nodes so, it can apply bindings to them            return[C1, C2]; }    }}

You can now include a template in the view, as follows:

<!-- -
Preprocessing API

ko.bindingProvider.instance.preprocessNode(node)

If defined, this function is called for each DOM node before the binding is processed. This feature can modify, delete, or replace nodes. Any new node must be inserted immediately before the node, and if any nodes are added or the node is deleted, the function must return an array of new nodes now in the document instead of nodes.

Knockoutjs 3.X API Fifth Advanced Applications (5) Using preprocessing extensions knockout binding syntax

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.