使用knockoutjs组件创建对话框

时间:2015-03-29 13:58:45

标签: javascript knockout.js knockout-components

我已经使用自定义绑定和knockout来显示jqueryui对话框,但我想使用knockout组件功能。

所以,我想写一些类似的东西:

<window params="isVisible: isVisible">
    //there will be some html
</window>

以后在代码的某处:

self.isVisible(true); //That would open window
//or
self.isVisible(false); //That would close window

问题是我不知道如何应用$(元素).dialog。当我注册knockout组件时,我只能获取该组件的容器元素,但不能注入元素。

ko.components.register('window', {
        viewModel: {
            createViewModel: function(params, componentInfo) {
                // - 'params' is an object whose key/value pairs are the parameters
                //   passed from the component binding or custom element
                // - 'componentInfo.element' is the element the component is being
                //   injected into. When createViewModel is called, the template has
                //   already been injected into this element, but isn't yet bound.
                // - 'componentInfo.templateNodes' is an array containing any DOM
                //   nodes that have been supplied to the component. See below.

                // Return the desired view model instance, e.g.:
                return new MyViewModel(params);
            }
        },
        template: ...
    });

因此,componentInfo.element是父节点,如果我使用$(componentInfo.element)应用对话框,我将设置为对话框父节点,然后我的窗口标记将是:

<div><!-- Dialog will be applyed there-->
    <window params="isVisible: isVisible">
        //there will be some html
    </window>
</div>

我认为它会起作用,但这里不需要额外的div ......或者这是完成工作的唯一方法?

什么是knockout.components的方法呢?感谢。

1 个答案:

答案 0 :(得分:0)

当我想使用Bootstrap v2'modal'功能构建一个用于托管对话窗口的Knockout组件时,我有类似的要求。我在页面的viewModel中使用了一个可观察的布尔值,最初设置为false。除非通过params传入可观察量,否则在初始化组件后,没有一种简单的方法可以与组件进行通信。

这个观察结果作为参数传递给参数中的<dialog-window>分量,例如

<dialog-window params="visible: showDialog">[content]</dialog-window>

然后使用了“模态”对话框的特殊绑定处理程序,但在您的情况下,您可以使用data-bind='visible: YourParam'属性直接绑定它。

然后主页可以简单地调用showDialog(true)以使对话框可见。

希望这有帮助。

相关问题