7

我正在尝试为引用模板的 twitter boostrap 弹出框创建自定义绑定,但是一旦创建弹出框内的内容的绑定部分,我遇到了问题。

我以前看过这个问题,但我觉得它们大多都很混乱,而且我非常接近一个可重用的解决方案,它可以按照我的意愿使用模板。

http://jsfiddle.net/billpull/Edptd/

// Bind Twitter Popover
ko.bindingHandlers.popover = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var tmplId = ko.utils.unwrapObservable(valueAccessor());
        var tmplHtml = $('#' + tmplId).html();
        var uuid = guid();
        var domId = "ko-bs-popover-" + uuid;
        var tmplDom = $('<div/>', {
            "class" : "ko-popover",
            "id" : domId
        }).html(tmplHtml);

        options = {
            content: tmplDom[0].outerHTML
        };

        var popoverOptions = ko.utils.extend(ko.bindingHandlers.popover.options, options);

        console.log($(element));
        console.log(element);

        $(element).bind('click', function () {
            $(this).popover(popoverOptions).popover('toggle');
            ko.applyBindings(bindingContext, document.getElementById(domId));
        });
    },
    options: {
        placement: "right",
        title: "",
        html: true,
        content: "",
        trigger: "manual"
    }
};

===编辑

根据下面的答案更新了代码,允许您在没有额外的 withProperties 绑定的情况下执行此操作

// Bind Twitter Popover
ko.bindingHandlers.popover = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // read popover options 
        var popoverBindingValues = ko.utils.unwrapObservable(valueAccessor());

        // set popover template id
        var tmplId = popoverBindingValues.template;

        // set popover trigger
        var trigger = popoverBindingValues.trigger;

        // get template html
        var tmplHtml = $('#' + tmplId).html();

        // create unique identifier to bind to
        var uuid = guid();
        var domId = "ko-bs-popover-" + uuid;

        // create correct binding context
        var childBindingContext = bindingContext.createChildContext(viewModel);

        // create DOM object to use for popover content
        var tmplDom = $('<div/>', {
            "class" : "ko-popover",
            "id" : domId
        }).html(tmplHtml);

        // set content options
        options = {
            content: tmplDom[0].outerHTML
        };

        // Need to copy this, otherwise all the popups end up with the value of the last item
        var popoverOptions = $.extend({}, ko.bindingHandlers.popover.options);
        popoverOptions.content = options.content;

        // bind popover to element click
        $(element).bind(trigger, function () {
            $(this).popover(popoverOptions).popover('toggle');

            // if the popover is visible bind the view model to our dom ID
            if($('#' + domId).is(':visible')){
                ko.applyBindingsToDescendants(childBindingContext, $('#' + domId)[0]);
            }
        });

        return { controlsDescendantBindings: true };
    },
    options: {
        placement: "right",
        title: "",
        html: true,
        content: "",
        trigger: "manual"
    }
};
4

4 回答 4

6

您需要使用我的老朋友自定义绑定

ko.bindingHandlers.withProperties = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // Make a modified binding context, with a extra properties, and apply it to descendant elements
        var newProperties = valueAccessor(),
            innerBindingContext = bindingContext.extend(newProperties);
        ko.applyBindingsToDescendants(innerBindingContext, element);

        // Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
        return { controlsDescendantBindings: true };
    }
};

然后,您需要在生成的 html 中添加一个 data-bind 属性:

    var tmplDom = $('<div/>', {
        "class": "ko-popover",
        "id": domId,
        "data-bind": "withProperties: { label: '" + viewModel.label() + "', required: '" + viewModel.required() + "' }"

我已经整理了一个jsFiddle 来展示这个。有几个陷阱,我必须为每个弹出框复制弹出框选项,否则它们都会以最后一组值结束。

    var popoverOptions = $.extend({}, ko.bindingHandlers.popover.options);
    popoverOptions.content = options.content;

而且我还必须仅在弹出窗口可见时才对弹出窗口应用绑定,否则它似乎试图绑定到整个页面。

$(element).bind('click', function () {
            $(this).popover(popoverOptions).popover('toggle');
            // If you apply this when the popup isn't visible, I think that it tries to bind to thewhole pageand throws an error
            if($('#' + domId).is(':visible'))
            {
                ko.applyBindings(viewModel, $('#' + domId)[0]);
            }
        });

这似乎也是双向的,因为您可以更改弹出窗口中的值并更新非弹出元素,但我不会撒谎,我没想到会发生这种情况!

于 2013-02-12T16:26:01.887 回答
3

这是 Knockout popover 绑定的另一个版本,它使用文档中定义的 html 模板。

看看这个小提琴:https ://jsfiddle.net/2cpcgz3o/

(function () {
    var templateEngine = new ko.nativeTemplateEngine();

    ko.bindingHandlers.customPopover = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var placement = allBindings.get("placement") || "top",
                trigger = allBindings.get("trigger") || "click",
                templateName = allBindings.get("customPopover") || null,
                $element = $(element);

            $element.popover({ placement: placement, trigger: trigger, html: true, content: "&nbsp;" });

            $element.on("inserted.bs.popover", function () {
                var container = $element.next().find(".popover-content")[0];
                if (templateName) {
                    ko.renderTemplate(templateName, viewModel, { templateEngine: templateEngine }, container);
                }
                else {
                    container.innerHTML = $element.attr("data-content");
                }
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $element.popover("destroy");
            });
        }
    };
})();

var model = {
  linkText: "Click me!",
  innerText: "Some fancy text"
};

ko.applyBindings(model);
<link href="https://cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<a data-bind="text: linkText, customPopover: 'popover-template', trigger: 'focus', placement: 'bottom'" tabindex="0" role="button"></a>

<script type="text/html" id="popover-template">
  <span data-bind="text: innerText"></span>
</script>

于 2017-03-22T17:43:59.187 回答
1

我在这里调整了另一个答案:https ://stackoverflow.com/a/16876013/1061602

这对我来说效果更好,尤其是对于一个简单的弹出框。

ko.bindingHandlers.popover = {
    init: function (element, valueAccessor) {
        var local = ko.utils.unwrapObservable(valueAccessor()),
            options = {};

        ko.utils.extend(options, ko.bindingHandlers.popover.options);
        ko.utils.extend(options, local);

        $(element).popover(options);

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).popover("destroy");
        });
    },
    options: {
        placement: "top"
    }
};

那么绑定是:

<span data-bind="popover: { content: mySimpleTextContent }"></span>

您显然可以覆盖其他选项。

于 2014-01-06T16:14:47.963 回答
0

稍微修改了 dodbrian的例子。内容绑定到一个可观察对象。

https://jsfiddle.net/SergeyZhilyakov/0zxamcj6/14/

var model = {
  linkText: "Hover me!",
  innerText: ko.observable("Please, wait...")
};

ko.bindingHandlers.popover = {
  init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    var $element = $(element);
    var placement = allBindings.get("placement") || "top";
    var trigger = allBindings.get("trigger") || "hover";
    var content = allBindings.get("popover");

    $element.popover({
      placement: placement,
      trigger: trigger,
      content: content()
    });

    var popover = $element.data("bs.popover");
    content.subscribe(function(newValue) {
      popover.options.content = newValue;
      popover.setContent();
      popover.$tip.addClass(popover.options.placement);
    });

    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
      $element.popover("destroy");
    });
  }
};

ko.applyBindings(model);

setTimeout(function() {
  model.innerText("Done!");
}, 3000);
body {
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>


<button type="button" class="btn btn-default" data-bind="text: linkText, popover: innerText, placement: 'bottom'">Comment</button>

于 2017-04-12T12:18:16.333 回答