从对象循环键动态传递 属性 引用
Dynamically pass property reference from object looping key
如何动态传递 属性 引用作为方法参数?
这就是 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);
}
}
});
如何动态传递 属性 引用作为方法参数?
这就是 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);
}
}
});