【问题标题】:Cannot close Durandal modal无法关闭 Durandal 模态
【发布时间】:2014-04-11 21:48:48
【问题描述】:

我已经阅读了几乎所有关于此的 stackoverflow 问题,但仍然无法正常工作...

我有一个模式,我在异步函数发生时用作“请稍候”。

视图模型是:

define(['plugins/dialog', 'knockout'], function (dialog, ko) {

    var CustomModal = function () {
        var self = this;
        this.msg = ko.observable(" Please Wait...");
    };

    CustomModal.show = function () {
        return dialog.show(new CustomModal());
    };

    CustomModal.close = function () {
        var self = this;
        dialog.close(self);
    };

    return CustomModal;
});

我还有其他带有“确定”按钮的模态框,它们关闭得很好,但是这个模态框是从我的主逻辑流程中打开的(我希望是关闭的)。

我在我的主代码中“需要”模态视图模型,这可以很好地显示它:

modalBusy.show();

但是,这并没有关闭对话框,这让我发疯了!

modalBusy.close();

调试时没有出错,但我的 close 方法中的“self”不是实际的视图模型对象,只是包含

    var CustomModal = function () {
        var self = this;
        this.msg = ko.observable(" Please Wait...");
    };

再咬一遍,显然这是错误的。

【问题讨论】:

  • 检查一下 - dfiddle.github.io/dFiddle-2.0/#modal - 您可以在那里重新创建一些工作示例。另外,您使用的是什么版本的 Durandal?我似乎记得使用带有 Bootstrap 3 或其他东西的 Durandal 2.1 的问题......
  • 这就是我开始编写代码的地方。 Durandal 2.0 和 Bootstrap 3.0 是我的项目中所拥有的。

标签: durandal


【解决方案1】:

您忘记使用prototype。您的关闭方法应该是:

CustomModal.prototype.close = function() {
    dialog.close(this);
}; 

按照您的编写方式,close() 是一种“静态”方法。而对于prototype,它是一个“类”方法。这就是为什么this 没有引用您所期望的。使用原型链,this 将引用实例化的对象。

更新:这里是一个示例,说明如何从可以工作的主代码中关闭模式,但是,它需要您重构 show() 方法。

define(['plugins/dialog', 'knockout'], function (dialog, ko) {
  var CustomModal = function () {
    this.msg = ko.observable(" Please Wait...");
  };

  CustomModal.prototype.show = function () {
    return dialog.show(this);
  };

  CustomModal.prototype.close = function () {
    dialog.close(this);
  };

  return CustomModal;
});

// from your main code, you use it like this    
var modal = new modalBusy();
modal.show();

// then, whenever you want to close it
modal.close();

【讨论】:

  • 激动了一分钟,但不,抱歉。 "TypeError: Object function () { ↵ var self = this; ↵ this.msg = ko.observable("Please Wait..."); ↵ } has no method 'close'↵
  • 这发生在我的主代码中的modalBusy.close(); 行。
  • 对不起 - 你能给我一个例子来说明你的意思吗?喜欢var myPleaseWaitModal = new modalBusy
  • 好的,问题是您在主代码中使用close() 方法的方式。您不能从主代码中调用modalBusy.close(),因为您没有对所创建对象的引用。你不这样做的原因是因为你在 show() 方法中用 new CustomModal() 实例化了它。
  • 太棒了。当您更新答案时,正在尝试在我的代码中尝试不同的组合!这真的有助于我理解一些我一直在努力从 asp.net 编码转换为 js 的概念,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多