Reputation: 4439
I am trying my first custom binding in knockout but cant seem to get it work. I got this sample from http://knockoutjs.com/documentation/custom-bindings.html.
script
ko.bindingHandlers.slideVisible = {
update: function (element, valueAccessor, allBindings) {
debugger;
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 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
}
};
html
<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);
</script>
jsfiddle link:http://jsfiddle.net/dingen2010/2gpL6/1/
Upvotes: 0
Views: 84
Reputation: 3702
It's working here, http://jsfiddle.net/YkeeB/ (using the same code) - but it's also using Knockout v3.0 (which is what the examples in the documentation on the Knockout website are using)
ko.bindingHandlers.slideVisible = {
update: function (element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 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
}
};
var viewModel = {
giftWrap: ko.observable(true)
};
ko.applyBindings(viewModel);
For Knockout v2.3.0 and below, there is no method ko.unwrap
. Instead, you have to use ko.utils.unwrapObservable
. Here is a fiddle with it working for v2.2.1, http://jsfiddle.net/yt4Gs/1/ .
Also, just for future reference when using JSFiddle, don't put script in the HTML section - even if it is inside <script>
tags. Put in the JavaScript section.
Upvotes: 1