Reputation: 3761
I'm aware that you use paranthesis in knockoutjs for the ff: * Unrapping observable function in code * Dive into objects with declarative binding
or when you have an object person with certain properties for ex: * person().firstname * person().age (The rightmost property doesn't need a parenthesis)
Now I have this kind of html/js:
<section>
<label>
<input data-bind="checked: displayGuitars" type="checkbox" />
Display Guitars
</label>
<div data-bind="fadeVisible: displayGuitars(), fadeDuration: 250">
<ul data-bind="foreach: products">
<li>
<span data-bind="text: model"></span>
</li>
</ul>
</div>
<div data-bind="dump: $data, enable: false"></div>
</section>
<script>
..................................some code
ko.bindingHandlers.fadeVisible = {
init: function (element, valueAccessor) {
// Start visible/invisible according to initial value
var shouldDisplay = valueAccessor();
$(element).toggle(shouldDisplay);
},
update: function (element, valueAccessor, allBindingsAccessor) {
// On update, fade in/out
var shouldDisplay = valueAccessor(),
allBindings = allBindingsAccessor(),
duration = allBindings.fadeDuration || 500; // 500ms is default duration unless otherwise specified
shouldDisplay ? $(element).fadeIn(duration)
: $(element).fadeOut(duration);
}
};
var vm = (function () {
var data = mockdata.getProducts();
var products = ko.observableArray(data);
var displayGuitars = ko.observable(false);
var vm = {
displayGuitars: displayGuitars,
products: products
};
return vm;
})();
ko.applyBindings(vm);
</script>
So basically what it does is that the div with fadeVisible binding is toggled show/hide depending whether the checkbox is checked or not, I tried removing the parenthesis in <div data-bind="fadeVisible: displayGuitars(), fadeDuration: 250">
and then suddenly the fadeVisible stopped working, the div no longer shows/hides when I check/uncheck the checkbox. My question is why do I need the parenthesis in the div with the fadeVisible binding, and if it does fall on any of the criteria I mentioned above which one is it?
Sir/Ma'am, your answers would be of great help. Thank you++
Upvotes: 2
Views: 610
Reputation: 19847
Your problem is that you don't have an unwrap
call for your valueAccessor
in the custom binding. It should look like this
init: function (element, valueAccessor) {
// Start visible/invisible according to initial value
var shouldDisplay = ko.unwrap(valueAccessor());
$(element).toggle(shouldDisplay);
},
This will work in Knockout2.3 If you have an older version its ko.utils.unwrapObservable
instead.
Here is a fiddle demonstrating it without the parens. BTW, in the future, when you have the code like this to demonstrate the issue, it helps to put together a fiddle of your own so people can look at the problem quickly.
Upvotes: 3