John Russell
John Russell

Reputation: 2247

Difficulties with JQuery UI Sortable inside Accordion backed by Knockout JS

See the jsFiddle link here for the UI I am trying to construct. First, the user selects a Conference. The Events for the selected Conference are shown in the Accordion, and each Event has Tables which are shown inside the Accordion as a plain html table. The user should be able to drag/drop the Tables and customize their Sort Order. All this is backed by Knockout JS which has worked great so far, but I've hit a block...

The first problem I had was "data-binding" the Accordion. I implemented the custom binding handler solution found here, and this seems to work great. However, I can't seem to reliably wire up the sortable functionality for the Table records.

I can't simply call $(".sortable tbody").sortable(); in the $(document).ready(function(){});. Although that works the for the first Conference, as soon as the SelectedConference changes, the sortable functionality is lost. I could add it to the update function of the Accordion's custom binder:

update: function (element, valueAccessor) {

            var options = valueAccessor();
            $(element).accordion("destroy")
            $(element).accordion({ active: "h3:last", collapsible: true });

            //TODO: add sortable call here
        }

That seems to work, but I'm new to custom binders. Is this innefficient? Are there better ways to implement the sortable functionality?

Thanks!

Upvotes: 1

Views: 725

Answers (1)

nemesv
nemesv

Reputation: 139808

Don't worry about custom binding handlers they are the right place to put this kind of logic.

However I would suggest that you should create a new custom binding only for the sortable logic because it has nothing to do with your accordions:

ko.bindingHandlers.sortable = {
    init: function (element, valueAccessor) {
        var options = valueAccessor() || {};
        $(element).sortable(options);
    }
}

Then you can use it your html:

<tbody data-bind="foreach: Tables, sortable: {}">

Demo JSFiddle.

Upvotes: 1

Related Questions