Archive

Posts Tagged ‘jquery’

jQuery UI drag and drop bindings for knockout.js

December 26, 2012 Leave a comment

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.

How to make jQuery tabs play nicely with Sammy.js

June 22, 2010 4 comments

jQuery tabs are very easy to use. In the HTML you do something like:
Read more…

Categories: Uncategorized Tags: , ,