---
title: "What are custom bindings in Knockout.js?"  
description: "What are custom bindings in Knockout.js?"  
author: "Revati S Misra"  
published: 2024-06-26  
updated: 2024-06-27  
canonical: https://www.mindstick.com/forum/160792/what-are-custom-bindings-in-knockout-js  
category: "knockcout js"  
tags: ["javascript", "knockout.js"]  
reading_time: 3 minutes  

---

# What are custom bindings in Knockout.js?

What are [custom](https://www.mindstick.com/blog/12298/use-custom-writing-services-to-get-through-the-finals) bindings in Knockout.js?

## Replies

### Reply by Ashutosh Patel

#### Knockout.js Custom Bindings

Custom bindings in Knockout.js are a powerful feature that allow developers to extend the behavior of HTML elements beyond the built-in bindings provided by Knockout.js They enable developers to create reusable, embedded bindings into specific application needs. Here is a detailed description of custom packaging.

#### Purpose of Custom Bindings

Knockout.js provides built-in bindings (such as `text`, `value`, `foreach`, etc.) that facilitate data binding between HTML elements and visual model properties. However, in complex applications, there may be requirements for actions or desired interactions that are not covered by these embedded threads. Custom bindings fill this gap by allowing developers to define their own bindings with custom logic and functionality.

#### Structure of a Custom Binding

A custom binding in Knockout.js consists of following steps,

**Binding Handler Function-** This is a JavaScript function that defines how a custom binding should behave. It usually includes parameters such as the binding element(s), the value accessor function (`valueAccessor`), and other optional parameters (`allBindings`, `viewModel`, `bindingContext`).

**Binding Definition Object-** This object defines the custom binding name (`init`, `update` functions, etc.). Here is the breakdown:

- **init function-** This function is called when Knockout.js first applies binding to an element. This is where you can configure any basic conditions, event handlers, subscriptions and more.
- **update function-** This function is called whenever the corresponding observable value changes. It allows you to update the DOM based on changes to the view model.
- **Optional properties**- You can also define optional properties such as `allowVirtualElements` and `hasRefresh` based on the needs of your custom binding.

## Example-

Here's a simple example of a custom binding that sets the visibility of an element based on a boolean observable:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" >
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.js"></script>
        <title>Custom Binding Example</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-12">
                <div></div>
                <p> click to hide: <span data-bind="fadeVisible: isVisible"> Toggle Visibility</span></p>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        ko.bindingHandlers.fadeVisible = {
        init: function(element, valueAccessor) {
            // Initially set the element to be hidden
            var value = valueAccessor();
            $(element).toggle(ko.unwrap(value)); // Using jQuery for simplicity

            // Toggle the visibility on click
            $(element).click(function() {
                value(!value());
            });
        },
        update: function(element, valueAccessor) {
            // Whenever the valueAccessor observable changes, update the element's visibility
            var value = valueAccessor();
            ko.unwrap(value) ? $(element).fadeIn() : $(element).fadeOut();
        }
    };

    // Example ViewModel
    function ViewModel() {
        this.isVisible = ko.observable(true); // Observable for controlling visibility
        this.isNotVisible = ko.observable(false);
    }

    // Apply bindings
    ko.applyBindings(new ViewModel());

    </script>
</body>
</html>
```

**In the example able-**\
**Custom Binding (fadeVisible)-** The custom binding handler `fadeVisible` is defined with the init and update functions.

In `init`, the visible origin of the element is determined by the observable `isVisible`, and a click event handler is attached to modify this observable.\
In `update` the visibility of an element is updated based on changes in the `isVisible` observable using jQuery f `adeIn()` and `fadeOut()` methods.

**Also, Read:** [Explain the role of observables and computed observables in Knockout.js?](https://www.mindstick.com/forum/160790/explain-the-role-of-observables-and-computed-observables-in-knockout-js)


---

Original Source: https://www.mindstick.com/forum/160792/what-are-custom-bindings-in-knockout-js

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
