When required Knockoutjs custom binding

154 Views Asked by At

trying to learn Knockoutjs.i have found a Knockoutjs custom binding related code but that is not very good.

<input data-bind="value: name" />
<hr/>
<div data-bind="fadeInText: name"></div>

ko.bindingHandlers.fadeInText = {
    update: function(element, valueAccessor) {
        $(element).hide();
        ko.bindingHandlers.text.update(element, valueAccessor);
        $(element).fadeIn(); 
    } 
};

var viewModel = {
    name: ko.observable("Bob")
};

ko.applyBindings(viewModel);

i just do not understand when people go for custom binding ?

1) if possible tell me few situation when custom binding would be option?

2) if anyone see the code then they can understand custom binding fadeInText and viewModel has no relation but still it is working. how ?

3) if there would be multiple view model then how could i specify viewmodel name with binding name at the time of binding ?

jsfiddle link of the above code http://jsfiddle.net/rniemeyer/SmkpZ/

4) how to achieve the same output without custom binding ? was it possible ?

please answer my question point wise. thanks

1

There are 1 best solutions below

8
RP Niemeyer On

Here are a few answers:

  1. custom bindings are useful in many scenarios and, in my opinion, shouldn't be used as a last resort. Anytime that you want to connect your DOM and data in a way that is not already supported by built-in bindings, then they are a good option. As I listed above, here is an article that could help clarify.

  2. The custom binding has a relationship with the view model indirectly by calling ko.bindingHandlers.text.update. So, it is effectively wrapping the actual text binding. The text binding reads the passed in value and displays.

  3. For multiple view models, this answer describes some options for handling multiple view models.

  4. Without a custom binding, you could choose to not use jQuery and use CSS (with consideration for browser support and prefixes). For example, you could immediately add a class to an element like:

With CSS like:

.message {
    opacity: 0;
    transition: opacity 2s ease-in;
}

.load {
    opacity: 1;
}

The element would start with opacity: 0 and immediately transition to opacity: 1 over 2 seconds.

I would not recommend using jQuery directly in your view model. Custom bindings are a tool available to you for these scenarios and provide much of the power that Knockout provides.

Hope this helps.