2016-08-03 6 views
0

私はノックアウトJSの新機能です、私はノックアウトJS viewmodelにAJAXの結果データをバインドしようとしていますが、データを表示するバインド中に問題に直面している、私はモデルとviewmodelを作成して私はajaxから結果を得ています。助けが必要。以下はノックアウトJSは、Ajaxの結果をbinnding

私のコードです:

// ajax on page load/// 
$.ajax({ 
    type: "POST", 
    dataType: "json", 
    url: baseUrl + 'api/xxx/xxx', 
    data: UserProfileModel, 
    success: function(data) { 
     result = data; 
     ////view model//// 
     userDetailsViewModel(result); 
    }, 
    error: function(error) { 
     jsonValue = jQuery.parseJSON(error.responseText); 
     //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 }); 
    } 
}); 

//// view model/// 
var userDetailsViewModel = function(result) { 
    console.log(result); 
    self = this; 
    self.user = ko.observable(new userModel(result)); 
}; 

$(document).ready(function() { 
    ko.applyBindings(userDetailsViewModel()); 
}); 

/// Model//// 
function userModel(result) { 
    this.name = ko.observable(); 
    this.userName = ko.observable(); 
} 
+0

userDetailsViewModelはselfを返す必要があります。現在は何も返されていません。したがって、ViewにはViewModelによって公開されるプロパティはありません。したがって、あなたのコードは動作していません。 –

答えて

0
  1. あなたuserDetailsViewModelundefinedを返す関数です。実際のビューモデルを作成する場合は、newを使用するか、return文を作成する必要があります。例えば:

    var UserDetailsViewModel = function(result) { 
        var self = this; 
        self.user = ko.observable(new UserModel(result)); 
    }; 
    
    var mainUserDetailsViewModel = new UserDetailsViewModel(data); 
    
  2. あなたはAJAXコールバックの範囲からあなたのviewmodelを更新する場合の参照を格納する必要があります。あるいは、ajaxの機能の一部をのviewmodelにすることもできます。最も簡単な例:

    var mainUserDetailsViewModel = new UserDetailsViewModel(data); 
    
    $.ajax({ 
        success: function(data) { 
        mainUserDetailsViewModel.user(new UserModel(data)); 
        } 
    }); 
    

    あなたapplyBindings呼び出しでこのモデルを使用していることを確認してください:

    ko.applyBindings(mainUserDetailsViewModel); 
    

注私はインスタンス化する必要がある機能のためにCapitalizedNamesを使用しました、とuncapitalizedNamesについてこれらの関数のインスタンスデフォルトの命名規則に従い、何が何であるかを把握するのに役立ちます。

+0

ありがとうございますが、UIへのバインディングは、現在の 'userModel'のコードでは、

+0

で実際に処理されませんすべて。したがって、 'name'は常に' undefined'になり、結果として空文字列になります。コンストラクタで 'this.name = ko.observable(result.Name)'のようなことをして設定する必要があります。 – user3297291

+0

ありがとう、しかし私はコンストラクタの値を渡したuserModel(結果)と私は何もエラーが発生しませんが、this.name = ko.observable(result [0] .name)またはthis.name = ko.observalbe(result .name)が表示されます。エラーlik userModelで未定義のプロパティ 'name'を読み取ることができません。 –