user1618825
user1618825

Reputation:

Custom Binding Calling Only Once

After this thread, knockoutjs custom binding is working, but the update function is working only once on clicking the same column again. How to make call the function again ?

After googling i found

ko.cleanNode(element)

How to apply this? Any ideas?

Here is the fiddle

Upvotes: 0

Views: 142

Answers (1)

Tomas Kirda
Tomas Kirda

Reputation: 8413

You need to store the state of last sorBy and if it matches then flip sort direction.

See updated fiddle: http://jsfiddle.net/tkirda/nHthh/4/

var lastSortBy = '';
var direction = 1;

ko.bindingHandlers.sortFunction = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var sortBy = ko.utils.unwrapObservable(valueAccessor());
        var items = viewModel.items;
        $(element).unbind('click.sort').bind('click.sort', function() {
            if (lastSortBy === sortBy){
                direction = direction === 1 ? -1 : 1;
            } else {
                direction = 1;
            }
            lastSortBy = sortBy;
            items.sort(function(a, b) {
                return direction * (a[sortBy]() < b[sortBy]() ? -1 : 1);
            });
        });
    }
}

Upvotes: 1

Related Questions