2014-02-16 55 views
1

我正在嘗試學習knockout.js並在頁面加載時從數據庫中查找數據。我有一切工作,除了成功的數據庫檢索後,textarea不會更新數據庫中的數據。有人告訴我我在做什麼錯誤的綁定?使用Knockout.js從數據庫綁定

<textarea id="taProgramOutcome" data-bind="value: programOutcomeText" rows="12" cols="20"></textarea> 


$(function() { 
function AppViewModel() { 
    this.programOutcomeText = "This is a review"; //initial binding works 

    var pageUrl = "/testapp/Service1.asmx"; 

    $.ajax({ 
     type: "POST", 
     url: pageUrl + "/GetReviews", 
     data: "{'disciplineRecordId': '" + 38 + "'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (result) {   //Database returns records, but the binding does not work. 
      this.programOutcomeText = 
ko.observable(result.d[0].disciplineOutcome); 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus); 
     } 
    }); 
} 

ko.applyBindings(new AppViewModel()); 
}); 

回答

0

2潛在的問題在這裏。 this中的success回調不是視圖模型。從一開始就應該是可觀察的。試試這個...

function AppViewModel() { 
    var self = this; 

    this.programOutcomeText = ko.observable("This is a review"); //initial binding works 

    var pageUrl = "/testapp/Service1.asmx"; 

    $.ajax({ 
     type: "POST", 
     url: pageUrl + "/GetReviews", 
     data: "{'disciplineRecordId': '" + 38 + "'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (result) {   //Database returns records, but the binding does not work. 
      self.programOutcomeText(result.d[0].disciplineOutcome); 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus); 
     } 
    }); 
} 
+0

謝謝,這很好。我可以看到我正在使用視圖模型的不同實例,但無法弄清楚如何使用正確的實例。 –

0

使用var self = this;在視圖模型和AJAX回調參照視圖模型領域的self。此外,請寫self.programOutcomeText = ko.observable("This is a review");而不是this.programOutcomeText = "This is a review";,然後寫self.programOutcomeText(result.d[0].disciplineOutcome);

$(function() { 
function AppViewModel() { 
    var self = this; 
    self.programOutcomeText = ko.observable("This is a review"); 
    var pageUrl = "/testapp/Service1.asmx"; 
    $.ajax({ 
     type: "POST", 
     url: pageUrl + "/GetReviews", 
     data: "{'disciplineRecordId': '" + 38 + "'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (result) {   
      self.programOutcomeText(result.d[0].disciplineOutcome); 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus); 
     } 
    }); 
} 

ko.applyBindings(new AppViewModel()); 
});