1

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

这是 ajaxsuccess函数响应数据的样子:

{
   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方法的第二个参数。

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

谢谢你。

4

1 回答 1

1

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

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);
       }
   }
});
于 2015-05-28T08:44:15.233 回答