knockout.js并使用版本2.3.0两次应用绑定

时间:2013-08-10 07:16:24

标签: knockout.js

我已升级到knockout.js 2.3.0,现在我收到错误Uncaught Error: You cannot apply bindings multiple times to the same element。申请绑定是第二次发生在renderTemplate以下,无论如何要解决它?

ko.bindingHandlers.eventsMap = {
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var accessor = valueAccessor();
            ko.renderTemplate(accessor.name, accessor.data, {}, element, 'replaceChildren');
        }
    };


<div id="events-template" data-bind="eventsMap: { data: eventsMap.currentLocation, name: 'event-template'}"></div>

<script type="text/html" id="event-template">
    <!-- ko if: $data -->
    <div><b data-bind="html: $data.City"></b></div><hr/>

    <div class="events-list" data-bind="with: $data.Events">
        <div data-bind="foreach: { data: $data, afterRender: function(element, index, data) { $(element).filter('.span12').find('a[rel!=nofollow]').attr('target', '_blank') }}">
            @Html.Partial(MVC.Shared.Views.Controls.Events)
        </div>
    </div>
    <!-- /ko -->
</script>

1 个答案:

答案 0 :(得分:3)

我想你可能会遇到this question。如果告诉Knockout您的绑定处理程序控制模板本身中子元素的绑定,则错误将消失。所以:

ko.bindingHandlers.eventsMap = {
        init: function(elem, valueAccessor) { 
            return {controlsDescendantBindings: true};
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var accessor = valueAccessor();

            ko.renderTemplate(accessor.name, accessor.data, {}, element, 'replaceChildren');
        }
    };

请参阅"before"fixed "after" fiddle