I looked at a lot of posts around global/local variables but I think I'm missing something. This is what I'm trying to get to:
var commandList = {
'command_a': function() {
socket.emit({action: 'a'});
},
'command_b': function() {
socket.emit({action: 'b'});
}
};
Instead of defining my list of commands, I would like to define them dynamically from an ajax call. This is my best attempt:
function getCommands() {
$.ajax({
type:'get',
url: '/getCommands',
data: data,
success: function(data) {
JSONdata = $.parseJSON(data);
// [{"action": "b", "command": "command_b"},{"action": "a", "command": "command_a"}]
var commandList = [];
jQuery.each(JSONdata, function( i, val ) {
command = val['command'];
action = val['action'];
service = {
[command]: function() {
socket.emit({action: [action]});
}
console.log(service[Object.keys(service)[0]]);
}
commandList.push(service);
});
}
});
}
The main problem is that in my loop, my action variable doesn't get replaced by a or b in service, which I assume is because action only gets defined when the function is called. The console.log returns:
function () {
socket.emit({action: [action]});
}
Instead of:
function () {
socket.emit({action: 'a'});
}
channeldefined?