问题是覆盖第一个对话框的第二个对话框args
,当关闭第二个对话框时,警报显示创建方法传递的对话框名称,当关闭第一个对话框时,名称也显示最后一个对话框的创建名称.
var Dialogs = Dialogs || (function () {
var _args = { //default args
name: "globalDialog"
}
var dialogName = "";
return {
create: function (args) {
_args = args;
dialogName = '#' + _args.name;
// create hide listener to current dialog attached to it's name
$(document).off('hidden.bs.modal', dialogName);
$(document).on('hidden.bs.modal', dialogName, function (e) {
alert(_args.name); //this show the last dialog name created
});
return this;
}
};
}());
//用法
Dialogs.create({name:"Dialog1"}); //create first dialog
Dialogs.create({name:"Dialog2"}); //create second dialog
上面的代码在彼此之上创建了两个对话框(模态)
我知道这个问题与类共享的静态成员有关,每次我需要创建新对话框时都需要实例化,但在 JavaScript
中无法执行此操作。
有任何解决方案或想法可以实现我正在寻找的东西。
最佳答案
尝试使用 OOP:
function Dialogs(args) {
this.args = args;
}
Dialogs.prototype.hide = function() {
for(var i = Dialogs.queue.length; i > 0; i--) {
if(Dialogs.queue[i - 1] === this) {
Dialogs.queue.splice(i - 1, 1);
}
}
}
Dialogs.prototype.show = function() {
this.hide();
Dialogs.queue.push(this);
}
Dialogs.queue = [];
Dialogs.showActiveName = function () {
if(Dialogs.queue.length) {
alert(Dialogs.queue[Dialogs.queue.length - 1].args.name);
}
}
Dialogs.create = function(args){
var out = new Dialogs(args);
Dialogs.queue.push(out);
return out;
}
var dialog1 = Dialogs.create({name: "a"});
var dialog2 = Dialogs.create({name: "b"});
dialog1.show();
Dialogs.showActiveName();
dialog2.show();
Dialogs.showActiveName();
dialog2.hide();
Dialogs.showActiveName();
关于javascript - 我的 javascript 包装器的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688053/