Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs "Unable to parse bindings" in plugin using ko.renderTemplate

I created a knockoutjs plugin that ultimately uses ko.renderTemplate in the "update" portion of it's binding handler. The code produces the expected output but also throws an "Unable to parse bindings" error.

A reproduction of this issue can be found here http://jsfiddle.net/rhoadsce/VSWK2/ on jsfiddle.

The javascript is as follows:

ko.plugin = function(configuration) {
    var self = this;
    self.content = configuration.content || '';
};

ko.bindingHandlers.plugin = {
    update: function(element, valueAccessor, allBindingsAccessor) {
        var viewModel = valueAccessor();

        $(element).append('<div id="pluginContainer"></div>');
        var $container = $(element).children('#pluginContainer');

        ko.renderTemplate("pluginTemplate", viewModel, {}, $container, 'replaceNode');
    }
};

$(function () {
    var vm = (function() {
        var plugin = new ko.plugin({ content: 'test content'});

        return {
            plugin: plugin
        }
    })();

    ko.applyBindings(vm);
});

The html is equally as simple.

<div data-bind="plugin: plugin"></div>

<script id="pluginTemplate" type="text/html"><span data-bind="text: content"></span></script>
like image 317
rhoadsce Avatar asked Oct 08 '22 09:10

rhoadsce


1 Answers

I think the issue is that KO is trying to apply bindings for the div's descendants (and it does this with the root viewmodel as context, instead of the inner plugin VM), but the call to ko.renderTemplate itself already applies bindings to the descendants (with the correct context).

To prevent this, make your bindingHandler's init method return { controlsDescendantBindings: true }. This prevents KO from trying to apply bindings. Here's the updated fiddle.

See here for additional info: http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html

like image 51
antishok Avatar answered Oct 13 '22 12:10

antishok