A Techno Blog, mainly about Java

Knockout Custom Bindings

I am continuing to work with KnockoutJs and I noticed a few examples that use custom bindings. This post does a great overview:

Knockout bindings consist of two methods: init and update. Creating a binding is as simple as creating an object with these two methods..

ko.bindingHandlers.yourBindingName = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
  update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

The init function – This is usually used to run one-time initialization code or to wire up event handlers …

The update function – provides a way to respond when associated observables are modified….

don’t actually have to provide both init and update callbacks ….

The element parameter – the DOM element that contains the binding…

The valueAccessor parameter – function that gives you access to what was passed to the binding. If you passed an observable, then the result of this function will be that observable (not the value of it). If you used an expression in the binding, then the result of the valueAccessor will be the result of the expression.

The allBindingsAccessor parameter – just a way to pass additional options to the binding, unless you choose to pass an object with multiple properties into your main binding.

The viewModel parameter – provides access to your overall view model for bindings outside of templates.  Most of the time the valueAccessor will give you the data that you want, but the viewModel parameter is particularly useful if you need an object to be your target when you call/apply functions.

ko.bindingHandlers.jqTabs = {
init: function(element, valueAccessor) {
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
update: function(element, valueAccessor, allBindingsAccessor) {
var dependency = ko.utils.unwrapObservable(valueAccessor()), //just to create a dependency
options = allBindingsAccessor().jqTabOptions || {}, //any additional options
selected = $(element).tabs(“option”, “selected”);  //restore selected index

//do in a setTimeout, as the DOM elements are not built yet when we are using bindings to create them
setTimeout(function() {
$(element).tabs(“destroy”).tabs(options).tabs(“option”, “selected”, selected);
}, 0);

August 22, 2012 - Posted by | Uncategorized |

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: