Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Knockout Custom Bindings

I have a Knockout custom binding handler that I want to call the foreach bindings functionality on within it and then call a callback function afterwards. I keep getting a "Uncaught Error: You cannot apply bindings multiple times to the same element. " error now as I try to do this.

My custom binding is pretty simple (typescript):

/// <reference path="knockout.d.ts" />
ko.bindingHandlers["postForeach"] = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        if (!allBindingsAccessor().postForeachCallback)
            throw "Callback not defined for postForeach binding!";

        //call foreach init functionality
        ko.bindingHandlers['foreach'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            //call foreach update functionality
            ko.bindingHandlers['foreach'].update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
            //call callback
            allBindingsAccessor().postForeachCallback();
    }
};

Is there something I am missing in constructing this?

Thanks!

EDIT:

Callback Function

self.populateMainContentWindow = function () {
                    var dataTable = $(this.tableId).dataTable();
        dataTable.fnDestroy();

                // create the datatable
                        var actualTable = this.jQuery(this.tableId);
        if (actualTable.length == 0) {
            return false;
        }

        // create the data table with options
        var newDataTable = actualTable.dataTable(this.options);

        // always set the width afterwards
        actualTable.css("width", "100%");
            };

Data Bind Signature (which is within a 'with' binding):

postForeach: array, postForeachCallback: $parent.viewModel().populateMainContentWindow
like image 600
Ben Nelson Avatar asked Jul 05 '26 08:07

Ben Nelson


1 Answers

Knockout uses the return value of init to determine whether it should process the element's descendants. You can either just return the value of the foreach.init function or specifically return { controlsDescendantBindings: true } from your init function:

init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    if (!allBindingsAccessor().postForeachCallback)
        throw "Callback not defined for postForeach binding!";

    //call foreach init functionality
    return ko.bindingHandlers['foreach'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},

Reference: http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html

like image 87
Michael Best Avatar answered Jul 07 '26 23:07

Michael Best