patternjavascriptMinor
reduce no. of lines
Viewed 0 times
reducelinesstackoverflow
Problem
I have the following type of many functions so many if condtions are there is there is any way to reduce no. of lines.
No of paramerter the callbacks may be increased in many functions.
Please suggest .
enter: function(request, callback, callback1){
request.on={};
if(callback==undefined && NodeClientUI.initdata.join!=undefined){
callback=NodeClientUI.initdata.join;
request.on.join=function(data){
callback(data);
};
}else if(callback!=undefined ){
request.on.join=function(data){
callback(data);
};
}
if(callback1==undefined && NodeClientUI.initdata.occupant!=undefined){
callback1=NodeClientUI.initdata.occupant;
request.on.occupant=function(data){
callback1(data);
};
}else if(callback1!=undefined ){
request.on.occupant=function(data){
callback1(data);
};
}
};No of paramerter the callbacks may be increased in many functions.
Please suggest .
Solution
Try this:
This permits you to call with callbacks defined as:
Request would get assigned in the same manner. If you can't pass a map of callbacks in this way, you could create a function which creates a global variable callbacks for you to use inside the method (just ignore the callback parameter passed to enter method and use callbacks instead):
enter: function(request, callbacks){
request.on={};
for(var key in callbacks) {
var callback = callbacks[key];
if(callback === undefined) {
callback = NodeClientUI.initData[key];
}
request.on[key]=function(data){
callback(data);
}
}
};This permits you to call with callbacks defined as:
var callbacks = {};
callbacks['join'] = function(data) { // join logic ... };
callbacks['occupant'] = function(data) { // occupant logic ... };
callbacks['stuff'] = undefined; // Takes on value of NodeClientUI.initData.stuff
...Request would get assigned in the same manner. If you can't pass a map of callbacks in this way, you could create a function which creates a global variable callbacks for you to use inside the method (just ignore the callback parameter passed to enter method and use callbacks instead):
var callbacks = {};
function addCallback(key, callback) {
callbacks[key] = callback;
}Code Snippets
enter: function(request, callbacks){
request.on={};
for(var key in callbacks) {
var callback = callbacks[key];
if(callback === undefined) {
callback = NodeClientUI.initData[key];
}
request.on[key]=function(data){
callback(data);
}
}
};var callbacks = {};
callbacks['join'] = function(data) { // join logic ... };
callbacks['occupant'] = function(data) { // occupant logic ... };
callbacks['stuff'] = undefined; // Takes on value of NodeClientUI.initData.stuff
...var callbacks = {};
function addCallback(key, callback) {
callbacks[key] = callback;
}Context
StackExchange Code Review Q#3434, answer score: 3
Revisions (0)
No revisions yet.