如何动态传递属性引用作为方法参数
这是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);
}
}
});