如何获取Knockout对话框进行更新

时间:2014-01-20 11:59:29

标签: javascript jquery knockout.js

我想要使用选定的文本更新此对话框弹出窗口。

<div data-bind="with: SelectedText">
    <div id="dialog" data-bind="dialog: {'autoOpen': false, 'title': textbatchTitle }, dialogVisible: $root.isMetadataDialogOpen">
        <div class="metadata">
            <label for="textbatchTitle">Title:</label> <span class="rotten">Why isen´t this updated with SelectText after pushing "Add New Text"?"</span>
            <input type="text" name="textbatchTitle" data-bind="value: textbatchTitle, valueUpdate: 'afterkeydown'" />
        </div>
    </div>
</div>

对话框似乎没有响应“with”-binding?

这是我的自定义绑定:

ko.bindingHandlers.dialog = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = ko.utils.unwrapObservable(valueAccessor()) || {};

        //do in a setTimeout, so the applyBindings doesn't bind twice from element being copied and moved to bottom
        setTimeout(function () {
            options.close = function () {
                allBindingsAccessor().dialogVisible(false);
            };

            $(element).dialog(ko.toJS(options));
        }, 0);

        //handle disposal (not strictly necessary in this scenario)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).dialog("destroy");
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().dialogVisible),
            $el = $(element),
            dialog = $el.data("uiDialog") || $el.data("dialog"),
            options = valueAccessor();

        //don't call dialog methods before initilization
        if (dialog) {
            $el.dialog(shouldBeOpen ? "open" : "close");

            for (var key in options) {
                if (ko.isObservable(options[key])) {
                    $el.dialog("option", key, options[key]());
                }
            }
        }
    }
};

这有什么问题? http://jsfiddle.net/qFjRW/

1 个答案:

答案 0 :(得分:1)

您没有将jquery ui包含为外部源:

Uncaught TypeError: Object [object Object] has no method 'dialog' 

请参阅http://jsfiddle.net/FXTHn

修改

由于您在对话框之外使用with: SelectedText,因此当update更改时,它不会调用SelectedText。尝试将其放入:

<div id="dialog" data-bind="dialog: {'autoOpen': false, 'title': SelectedText().textbatchTitle }, dialogVisible: $root.isMetadataDialogOpen">
    <div data-bind="with: SelectedText">
        <div class="metadata">
            <label for="textbatchTitle">Title:</label> <span class="rotten">Why isen´t this updated with SelectText after pushing "Add New Text"?"</span>
            <input type="text" name="textbatchTitle" data-bind="value: textbatchTitle, valueUpdate: 'afterkeydown'" />
        </div>
    </div>
</div>

http://jsfiddle.net/FXTHn/1/