2015-09-22 78 views
0

我使用這裏的例子設置了一個自定義對話框:Durandal 2.0 custom dialog,它工作正常。在這個例子中,我等同於「現有視圖」是我的登錄表單,它具有通常的用戶名/密碼/登錄按鈕。如何從該對話框中的viewmodel關閉自定義的Durandal對話框?

登錄按鈕提交表單,並執行遠程webapi調用來驗證用戶。所有的作品都很好。在登錄成功的情況下,我想關閉對話框,但我無法使其工作 - 它只是保持打開狀態。

在我看來,對話框預計爲dialog.close(customModal,...'),因爲這是打開它的視圖模型。但是因爲我在我的登錄視圖中處於低級別,所以如何從對話框中的視圖模型中喚醒關閉當前對話框的願望?

主視圖模型調用的作用:

Existing = require('./login') 
    ... 

    this.dialog = new CustomDialog('My title', new Existing()); 
    this.dialog.show().then(function (response) { 
     //check login results and do whatever is necessary here... 
    }); 

CustomModal視圖模型:

define(['plugins/dialog'], function (dialog) { 
    var CustomModal = function (title, model) { 
     this.title = title; 
     this.model = model; 
}; 

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

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

return CustomModal; 

});

並登錄視圖模型:

define([ 
    'jquery', 
    'knockout', 
    'datacontext', 
    'plugins/dialog' 
], function ($, ko, dc, dialog) { 
    var vmLogin = function() { 
     var self = this; 

     self.user = ko.observable(''); 
     self.password = ko.observable(); 

     self.doLogin = function() { 

      return dc.doLogin(self.user, self.password) 
       .done(function (data) { 
        if (data.success == true) { //logged in ok 
         dialog.close(self); 
        } else { //failed to log in 
         //todo: display error message 
        } 
       }) 
      .fail(function (jqXHR, textStatus, errorThrown) { 
       // 
      }); 
     } 
    }; 

    return vmLogin; 
}); 

回答

0

嗯,我有種重構代碼來解決這個問題。我決定不讓中間人「自定義對話框」,而是將登錄名稱稱爲自定義對話框。所有我需要做的是添加在closeshow方法(可能甚至沒有需要的原型是誠實的),並直接使用那些:

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

    self.user = ko.observable(''); 
    self.password = ko.observable(); 

    self.doLogin = function() { 
     var self = this; 

     return dc.doLogin(self.user, self.password) 
      .done(function (data, p2, p3) { 
       if (data.success == true) { //logged in ok 
        dialog.close(self, null); 
       } else { //failed to log in 
        //TODO: Show message 
       } 
      }) 
     .fail(function (jqXHR, textStatus, errorThrown) { 
      // 
     }); 
    } 

    vmLogin.prototype.close = function() { 
     dialog.close(this, null); 
    }; 

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

}; 

return vmLogin;