ghiotion
ghiotion

Reputation: 285

knockout - wait for multiselect data to populate before selecting values

I've got a kendoMultiSelect widget in my page that gets it's values from a JSON call and gets the selected values from a separate JSON call.

<select id="locations" data-bind="kendoMultiSelect: {data: locations_list, value: spm.locations}" class="form-control"></select>

function SchedulerProfileModel(){
    var self = this;
    self.locations = ko.observableArray();
}

function SchedulerProfile(params) {
    var self = this;
    self.locations_list = ko.observableArray(['--------']);
}

function MakeAjaxCalls(){
    $.ajax({
      url: '/api/location',
      data: {"q": JSON.stringify(filters)},
      dataType: "json",
      contentType: "application/json",
      success: function(data) { 
        for (var i = data.objects.length - 1; i >= 0; i--) {
            self.locations_list.push(data.objects[i].name+": "+data.objects[i].state_province);
        };
      }
    });
}

function CurrentSchedulerProfile() {
    //does the current user already have a shceduler profile?  
    $.ajax({
      url: '/api/schedulerprofile',
      data: "q=" + JSON.stringify({"single":true,"filters":[{"name": "user_id", "op": "eq", "val": self.user_id()}]}),
      dataType: "json",
      contentType: "application/json",
      success: function(data) { 
        self.requesttype = "put";

        for (var i = data.locations.length - 1; i >= 0; i--) {
            self.spm.locations.push(data.locations[i].name+": "+data.locations[i].state_province);
        };
    });
}

$.when(MakeAjaxCalls()).then(CurrentSchedulerProfile);

This works fine in dev - it all times up nicely. The problem is that when I deploy to production the locations_list observable doesn't seem to populate before the spm.locations observable. The locations_list is pretty big. In other words, I get no selected values in the multiselect. The values of the observables are correct on the page - I can output the text of spm.locations and it's right. I've tried playing around with the ratelimit but that doesn't seem to work either. I've even tried making the two ajax calls synchronous and that doesn't help. I feel like the secret sauce is in the ratelimit but what's the way to make one observable wait on a different observable to populate?

Upvotes: 0

Views: 184

Answers (1)

Max Brodin
Max Brodin

Reputation: 3938

You can subscribe on your observable array change

 self.spm.locations.subscribe(function (newValue) {
   if (newValue && newValue.length > 0) {
      // newValue is set, we can populate our locations_list now
   }
}, this)

BTW you don't want push values to the observableArray one by one, push it into temp array, see this post

Upvotes: 2

Related Questions