带有bootstrap popover的Knockout事件

时间:2016-12-01 09:52:48

标签: twitter-bootstrap knockout.js

我有一个用于popover的自定义绑定:

init = (element: any, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor, viewModel?: any, bindingContext?: KnockoutBindingContext) => {
        var $elem = $(element);
        var popover = $elem.popover({
            placement: 'auto',
            content: function () {
                return $('#' + valueAccessor() + " > div");
            },
            html: true,
            container: 'body'
        })
}


<div class="pover">
    <div>
        <span data-bind="click: function(){alert('213')}">test</span> 
    </div>
</div>

所以你第一次打开popover - 它会显示文字,点击事件工作正常。 第二次打开popover时它是空的。当你隐藏弹出框时,B / c dom被破坏。 我怎么能避免这个?我无法克隆html,b / c点击事件绑定会被破坏......

我的解决方案,请告诉我可能出现的问题?

var popover = $elem.popover({
            placement: 'auto',
            content: function () {
                $("#single-popover").remove();
                $('body').append('<div id="single-popover">' + $("#popoverTemplate").html() + '</div>');
                ko.cleanNode($('#single-popover')[0]);
                ko.applyBindings(bindingContext, $('#single-popover')[0]);
                return $('#single-popover');
            },
            html: true,
            container: 'body'
        })

1 个答案:

答案 0 :(得分:0)

这对你有用http://jsfiddle.net/LkqTU/32668/

ko.bindingHandlers.popover = {
  init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    ko.bindingHandlers.value.init(element, valueAccessor, allBindings);
    var source = allBindings.get('popoverTitle');
    var sourceUnwrapped = ko.unwrap(source);
    $(element).popover({
      trigger: 'focus',
      title: sourceUnwrapped,
      placement: 'auto',
      content: function() {
        return  ko.unwrap(valueAccessor()) 
      },
      html: true,
      container: 'body'
    });
  },
  update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    var value = valueAccessor();
    ko.bindingHandlers.value.update(element, valueAccessor);
  }
};