从对象循环键动态传递属性引用

时间:2015-05-28 08:41:27

标签: javascript knockout.js knockout-2.0 knockout-mvc knockout-3.0

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

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

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

谢谢。

1 个答案:

答案 0 :(得分: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);
       }
   }
});