2011-07-25 9 views
9

我想了解什麼是用淘汰賽定義和組織我的js視圖模型的最佳做法。我不是天才的js所以......爲什麼在knockout.js的例子中,viewmodel有時被定義爲一個函數,其他的時候被定義爲直接變量?

好了,所以在很多的例子視圖模型被定義爲:

var viewModel = { 
    firstName: ko.observable("Bert"), 
    lastName: ko.observable("Bertington"), 

    capitalizeLastName: function() { 
     var currentVal = this.lastName();  // Read the current value 
     this.lastName(currentVal.toUpperCase()); // Write back a modified value 
    } 
}; 

的另一種方法是創造一種構造:

function viewModel() { 
    this.firstName = ko.observable("Bert"); 
    this.lastName = ko.observable("Bertington"); etc............. 

我的直覺是創造我的ViewModels的功能/班,但發現定義函數時,裏面的東西像Ajax調用等等,我沒能更新函數定義裏面的視圖模型變量。我必須先定義viewModel,然後在之後「添加」函數?

function LogOnModel() { 
    this.userName = ko.observable(""); 
    this.password = ko.observable(""); 
    this.userNameExists = ko.observable(true); 
    this.passwordCorrect = ko.observable(true); 
    this.returnURL = ko.observable(document.location.href.replace("http://" + location.host,"")); 
    this.login = function() { 
     $.ajax({ 
      type: 'POST', 
      contentType: 'application/json; charset=utf-8', 
      data: ko.toJSON(this), 
      dataType: 'json', 
      url: 'Account/LogOn', 
      success: function (result) { 
       this.userNameExists(result["UserNameExists"]); 
       this.passwordCorrect(result["PasswordCorrect"]); 
       alert(userLogOnModel.userNameExists); 
      } 
     }); 
    this.loginFormFilled = ko.dependentObservable(function() { 
     if ((this.userName() != "") && (this.password() != "")) 
      return true; 
     else 
      return false; 
    }, this); 

} 

在上面的登錄函數不能更新userNameExists或passwordCorrect變量..我試了一堆不同的語法。當我提出這個功能了,它工作正常構造的..

我只是不明白什麼是創建排序函數的構造函數,如果沒有成員函數可以在裏面它存在的目的是什麼?我錯過了什麼?謝謝!

回答

8

你的問題很可能的this在回調的價值。有幾種方法可以完成這項工作:

$ .ajax接受context參數,因此您可以將context: this添加到傳遞給它的選項中。

你也可以this.login內將其設置爲一個變量,在結果使用的變量。這將是這樣的:

this.login = function() { 
    var that = this; 
    .... 
    success: function (result) { 
       that.userNameExists(result["UserNameExists"]); 
       that.passwordCorrect(result["PasswordCorrect"]); 
      } 
} 

或者你可以在你的成功的功能結合到this,這將確保該函數調用與this正確的值。它會像

success: function (result) { 
       this.userNameExists(result["UserNameExists"]); 
       this.passwordCorrect(result["PasswordCorrect"]); 
       alert(userLogOnModel.userNameExists); 
      }.bind(this) 

因爲,您使用$ .ajax,第一個選項是最簡單的。

+0

嘿感謝!很棒。當我沒有傳遞上下文什麼是成功函數中的上下文(this)?空值? –

+0

默認情況下,'this'將被設置爲一個包含所有$ .ajax設置的對象。 –

+0

這是一篇關於knockoutjs的好文章。這個問題和其他幾種常見的基因敲除的問題:http://www.devcurry.com/2013/07/knockoutjs-cheat-sheet-for-beginners.html –

相關問題