简体   繁体   English

如何使用敲除JS更改下拉选择之前提示用户

[英]How to prompt user before changing dropdown selection with knockout js

I have a drop down in my HTML like this: 我的HTML如下所示:

<select id="test" style="padding: 5px; width: 200px;" 
    data-bind="options:workspaces,
    optionsText:'Category',
    value:chosenWorkspace,
    "></select>

And I have a subscribe on the chosenWorkspace: 我有一个对selectedWorkspace的订阅:

self.chosenWorkspace.subscribe(function (newWorkspace) {
    if (newWorkspace) {
        ko.mapping.fromJS(ko.mapping.toJS(newWorkspace), {}, self.workspace);
        self.isDirty = ko.dirtyFlag(self.workspace);
    }
});

When the user selects a different value from the drop down, I want to prompt them if they really want to change values since they would lose changes to the current item. 当用户从下拉列表中选择其他值时,我想提示他们是否真的要更改值,因为他们会丢失对当前项目的更改。 If they say they don't want to change, I don't want the chosenWorkspace to be updated. 如果他们说不想更改,那么我就不想更新chosenWorkspace

I've tried several things including an event: {change: promptUser} to the drop down that I was hoping would prompt the user and if they choose to cancel it would not update anything else. 我已经尝试了一些事情,包括一个event: {change: promptUser}下拉到我希望会提示用户的下拉菜单中,如果他们选择取消,则不会更新其他任何内容。 However, when I debugged it turned out that the subscribe was executing before the change event, so even if they cancelled the chosenWorkspace still changed. 但是,当我调试时,事实证明subscribe是在更改事件之前执行的,因此即使他们取消了chosenWorkspace仍然发生了更改。

Is there a way that when the user switches values in the drop down I can prompt them and stop the change if they choose that? 当用户在下拉菜单中切换值时,是否可以提示他们并停止更改(如果他们选择了此方法)?

You may want to try with a computed observable so you can set up your confirmation in its write part: 您可能需要尝试使用可计算的可观察值,以便可以在其可write部分设置确认:

var model = function() {
  var self = this;

  self.workspaces = [{ Category: 'a'},{ Category: 'b'},{ Category: 'c'}];
  self.chosenWorkspace = ko.observable();

    this.computedChosenWorkspace = ko.computed({
        read: function () {
            return self.chosenWorkspace();
        },
        write: function (value) {
            //We check for null value to avoid showing the confirmation the first time
            if(self.chosenWorkspace() == null || confirm("Are you sure?")){
                self.chosenWorkspace(value);
            }
            else{
                //Notify so the control keep its old value
                self.computedChosenWorkspace.notifySubscribers();
            }
        },
        owner: this
    });


};

var m = new model();

ko.applyBindings(m)

And in your HTML: 在您的HTML中:

<select id="test" style="padding: 5px; width: 200px;" 
    data-bind="options:workspaces,
    optionsText:'Category',
    value:computedChosenWorkspace"></select>

Here's the fiddle: https://jsfiddle.net/j9opb5bc/1/ 这是小提琴: https : //jsfiddle.net/j9opb5bc/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM