Search code examples
javascriptknockout.jsknockout-2.0knockout-mvcknockout-3.0

Dynamically pass property reference from object looping key


How do I dynamically pass a property reference as a method arguments ?

This is what ajax success function response data look like:

{
   users: {
      data: {}
   },
   countries: {
      data: {}
   },
   states: {
     data: {}
   }
}

This is example how i store the data previously:

var users = ko.observable();  
var countries = ko.observable();  
var states = ko.observable();

var store = function(data, observable)
{
    observable(data);
}

$.ajax({
   //... ajax options...

   success: function(response)
   {
       // This is how i store the data previously
       store(response.users.data, users);
       store(response.countries.data, countries);
       store(response.states.data, states);
   }
});

And this is example what I have try so far:

$.ajax({
   //... ajax options...

   success: function(response)
   {
       // This is how i want to achieve
       ko.utils.objectForEach(response, function(key, data)
       {
           store(data.data, key);
       });
   }
});

But unfortunately I just only pass the text string to the 2nd arguments of store method.

Any help and suggestions would be appreciated!

Thank you.


Solution

  • Make them properties of an object, then use strings:

    var obj = {
        users: ko.observable(),
        countries: ko.observable(),
        states: ko.observable()
    };
    
    var store = function(data, observable)
    {
        var prop = obj[observable];
        if (prop) { // Just being defensive
            prop(data);
        }
    };
    
    $.ajax({
       //... ajax options...
    
       success: function(response)
       {
           var key;
           for (key in response) {
               store(response[key].data, key);
           }
       }
    });