这与您的具体问题略有不同,但这是使用引导模式的另一种方法。
您可以使用包含引导程序modal
和绑定的自定义template
绑定。
绑定可能如下所示:
ko.bindingHandlers.modal = {
init: function(element, valueAccessor, allBindings, vm, context) {
var modal = valueAccessor();
//init the modal and make sure that we clear the observable no matter how the modal is closed
$(element).modal({ show: false, backdrop: 'static' }).on("hidden.bs.modal", function() {
if (ko.isWriteableObservable(modal)) {
modal(null);
}
});
//template's name field can accept a function to return the name dynamically
var templateName = function() {
var value = modal();
return value && value.name;
};
//a computed to wrap the current modal data
var templateData = ko.computed(function() {
var value = modal();
return value && value.data;
});
//apply the template binding to this element
ko.applyBindingsToNode(element, { template: { 'if': modal, name: templateName, data: templateData } }, context);
//tell KO that we will handle binding the children (via the template binding)
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor) {
var data = ko.utils.unwrapObservable(valueAccessor());
//show or hide the modal depending on whether the associated data is populated
$(element).modal(data ? "show" : "hide");
}
};
现在,您将在页面上绑定一个模式,例如:
<div class="modal hide fade" data-bind="modal: currentModal"></div>
currentModal
将是一个 observable,您使用包含name
(模板名称) 和data
.
其工作方式是,如果currentModal
已填充,则使用当前模板和数据显示模式。如果currentModal
为空,则模式关闭。
这是一个如何工作的示例:http: //jsfiddle.net/rniemeyer/NJtu7/