如何动态地将属性引用作为方法参数传递?

这就是ajax success函数响应数据的样子:

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


这是我以前存储数据的示例:

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);
   }
});


这是到目前为止我尝试过的示例:

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

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


但是不幸的是,我只将文本字符串传递给store方法的第二个参数。

任何帮助和建议,将不胜感激!

谢谢。

最佳答案

使它们成为对象的属性,然后使用字符串:

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);
       }
   }
});

09-19 13:42