为knockout.js数据绑定加载多个远程数据源

时间:2015-03-03 21:11:58

标签: javascript ajax knockout.js viewmodel

我正在使用knockout.js向导,需要从多个远程数据源(通过AJAX)获取数据,然后才能正确呈现向导中的下拉菜单。

此外,还有4个下拉菜单,而#1和#2可以先加载,#3和#4取决于前两个选择的选项。

到目前为止,我已经尝试过使用jQuery promises,并且只是嵌套数据调用及其相关的回调,但有没有更好的方法来构建我的向导的视图模型代码?

以下是一些数据加载代码。如果需要,我很乐意提供更多。

var postobj = {
    id: workoutId
};
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj);
var getDiet = $.post("./Diet/GetDietUsingId", postobj);
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj);
// When all three are successful - I haven't gotten the when syntax to actually work yet
$.when(getWorkout, getDiet, getFeedback).done(function (workout, diet, feedback) {
    //each of the parameter is an array
    renderCharts(workout[0], diet[0], feedback[0])
    // Here are more dropdowns that depend on the choices from the above ones
    self.suggestedWorkouts = ko.observableArray();
    // pseudo-code for data call for getting suggested workouts
    $.post("./RowingWorkouts/GetSuggested", { id: selectedOldWorkout }, function(result) { 
        self.suggestedWorkouts(result);
    });

});

这会更深入几个级别,如果可能的话,我宁愿避免它。是否有任何我缺少的设计模式或者这种编码错误?

1 个答案:

答案 0 :(得分:1)

您可以使用lazy loading observable将数据导入viewModel observables,并计算为在加载父级observable时订阅。

function ViewModel() {
   this.workout = ko.onDemandObservable(ViewModel.prototype.getWorkout, this);
   this.diet = ko.onDemandObservable(ViewModel.prototype.getDiet, this);
   this.feedback= ko.onDemandObservable(ViewModel.prototype.getFeedback, this);
   this.suggestedWorkouts = ko.observable();

   ko.computed(ViewModel.prototype.listsLoaded, this);
}

ViewModel.prototype.listsLoaded= function () {    
   if (this.workout.loaded() && this.diet.loaded() && this.feedback.loaded()) {
        this.loadSuggestedWorkouts();
   }
}

ViewModel.prototype.getWorkout = function () {
   ...
}

ViewModel.prototype.getDiet = function () {
   ...
}

ViewModel.prototype.getFeedback = function () {
   ...
}

ViewModel.prototype.loadSuggestedWorkouts = function () {
  ...
}