Home > Uncategorized > jQuery UI drag and drop bindings for knockout.js

jQuery UI drag and drop bindings for knockout.js

If there’s some functionality you need in your knockout app, just add custom bindings. Here’s one way to enable drag and drop by bringing in the jQuery UI library to do it all for us. First, the drag binding:

ko.bindingHandlers.drag = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, context) {
        var value = valueAccessor();
        $(element).draggable({
            containment: 'window',
            helper: function(evt, ui) {
                var h = $(element).clone().css({
                    width: $(element).width(),
                    height: $(element).height()
                });
                h.data('ko.draggable.data', value(context, evt));
                return h;
            },
            appendTo: 'body'
        });
    }
};

The value for the binding is a function that should return some object or value that describes what is being dragged, e.g. here the view model of the draggable element has a save function that returns the persistent data of the object:

<div data-bind="drag: save">;

Then to allow it to be dropped somewhere, we need the drop binding:

ko.bindingHandlers.drop = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, context) {
        var value = valueAccessor();
        $(element).droppable({
            tolerance: 'pointer',
            hoverClass: 'dragHover',
            activeClass: 'dragActive',
            drop: function(evt, ui) {
                value(ui.helper.data('ko.draggable.data'), context);
            }
        });
    }
};

Again, the value is a function, which this time receives the dragged data as its first argument, so it’s nice and symmetrical:

<div data-bind="drop: dropped">;

If the drop regions are contained in scrollable areas, then decent autoscrolling is a must, and it can be implemented from the drag binding using a timer. There’s a working implementation in my Nimbah project.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: