我有一个
jquery ui对话框,在表单上有一个knockoutjs提交绑定.可以通过按取消按钮,按对话框标题栏上的关闭按钮,按下转义或按保存按钮来关闭对话框.我的意图是取消,转义和标题栏关闭事件应该在不应用任何操作的情况下关闭对话框,而按Enter或单击“保存”应该执行对话框操作.除了输入键之外,一切都按预期工作,这会导致取消事件,而不是在提交事件中.
我创建了一个jsfiddle来说明这一点,并在下面包含代码以供参考.
我为冗长的代码道歉…
基因
<!-- ko with: dialog --> <div id="taskdlg" class="resizeableDialog" data-bind="dialog: {autoOpen: false,title: 'Edit task',height: 200,width: 500,modal: true,close: updateCloseState},openWhen: open"> <form data-bind="submit: update"> <table> <tr> <td style="width: 100px;"><label for="tasktitle">Title</label></td> <td width="*"> <input id="tasktitle" type="text" placeholder="Task name" data-bind="value: titletext,valueUpdate: 'afterkeydown'" /> </td> </tr> <tr> <td><button style="float: left;" data-bind="click: cancel">Cancel</button></td> <td><button style="float: right;" type="submit">Save</button></td> </tr> </table> </form> </div> <!-- /ko --> <button data-bind="click: editTask">Edit</button> <span data-bind="text: task"></span>
javascript如下:
ko.bindingHandlers.dialog = { init: function(element,valueAccessor,allBindingsAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()); setTimeout(function() { $(element).dialog(options || {}); },0); //handle disposal (not strictly necessary in this scenario) ko.utils.domNodeDisposal.addDisposeCallback(element,function() { $(element).dialog("destroy"); }); },update: function(element,allBindingsAccessor) { var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().openWhen); $(element) .dialog(shouldBeOpen ? "open" : "close"); } }; function Task(name) { var self = this; this.title = ko.observable(name); this.toString = function() { return "Task: " + self.title(); }; } function TaskDialog(viewmodel) { var self = this; this.viewmodel = viewmodel; this.task = ko.observable(); this.open = ko.observable(false); this.titletext = ko.observable(); this.editTask = function(task) { self.task(task); self.titletext(task.title()); self.open(true); } this.update = function() { var task = self.task(); task.title(self.titletext()); self.open(false); } this.updateCloseState = function() { if (self.open()) self.open(false); } this.cancel = function() { self.open(false); } } function viewmodel() { var self = this; this.dialog = ko.observable(new TaskDialog(self)); this.task = ko.observable(new Task('sample task')); this.editTask = function() { self.dialog().editTask(self.task()); } }; ko.applyBindings(new viewmodel());