2014-03-26 123 views
0

我試圖更新JavaScript視圖模型,只要通過對服務器進行ajax調用來單擊按鈕,並且頁面在第一次單擊後似乎沒有選擇新分配的viewmodel。當viewModel更改時刷新Knockout綁定

我有一個樣品的jsfiddle here

下面是我簡單的ViewModel

var viewModel = { 
model: null 
}; 

按鈕單擊事件處理程序,我保證申請綁定只調用一次

$('#btnSearch').click(function() { 
    // In actual scenario this data is returned from server side code 
    var playerData = searchPlayers($('#drpCountry').val()); 
    // Data returned from server is then assigned to viewModel 
    viewModel.model = playerData; 
    if ($('#hdnKOHasBinded').val() === '0') { 
     ko.applyBindings(viewModel); 
     $('#hdnKOHasBinded').val('1'); 
    } 
}); 

請幫助

回答

0

我已更新您的fid經過若干修改和註釋的DLE修復與如何遵循淘汰賽慣例,以及JavaScript的約定兩個問題:http://jsfiddle.net/azurelogic/NsKPQ/2/

JS:

//Capitalize your object constructors if they are supposed to be created with 'new' 
function Player(name, age) { 
    //these would still work if they were like this: this.name = name; 
    //they only need to be observable if you plan to change 
    //one of the properties without swapping out the whole object 
    this.name = ko.observable(name); 
    this.age = ko.observable(age); 
} 

function searchPlayers(country) { 
    var players = null; 
    if (country === 'spain') { 
     players = [ 
     new Player('Nadal', 28), 
     new Player('Ferrer', 32), 
     new Player('Lopez', 29)]; 
    } else if (country === 'swiss') { 
     players = [ 
     new Player('Federer', 32), 
     new Player('Wawiranka', 28)]; 
    } 
    return players; 
} 

var viewModel = { 
    //changed the name from model to players and made the array observable. This is what drives your ability to update the DOM 
    players: ko.observableArray() 
}; 

$(function() { 
    $('#btnSearch').click(function() { 
     // In actual scenario this data is returned from server side code 
     var playerData = searchPlayers($('#drpCountry').val()); 
     // Data returned from server is then assigned to viewModel 
     viewModel.players(playerData); 
    }); 

}); 

//Just go ahead and apply bindings immediately 
ko.applyBindings(viewModel); 

HTML:

<div> 
    <select id="drpCountry"> 
     <option value="spain">spain</option> 
     <option value="swiss">swiss</option> 
    </select> 
</div> 
<input type="button" id="btnSearch" value="Search" /> 
<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: players"> 
     <tr> 
      <td data-bind="text: name"></td> 
      <td data-bind="text: age"></td> 
     </tr> 
    </tbody> 
</table> 
+0

感謝提供清晰的推理背後的變化 – Swamy

相關問題