开发者

How do I relay dynamic parameters passed into a functionA() to functionB() called within functionA()

I'm trying to relay dynamic parameters from a web page into a function, which then passes them to a call inside the function. For example, take the simplified snippet below, as it is now, passing in the parameters directly is not problem. But how do I pass in a parameter which colorbox accepts without making a parameter for showColorbox() for every possible colorbox parameter?

function showColorbox(title, url, width, height, modal, params) {

    $.colorbox({title:title, href:url, width:width, height:height, opacity:0.7});

}

For instance, colorbox accepts passing in an event function, such as below if I called colorbox directly:开发者_JS百科

    $.colorbox({title:title, href:url, width:width, height:height, opacity:0.7, 
                onComplete: function() {
                                 $.colorbox.resize();
                             } 
              });

So, without adding some code or making another parameter and parsing it out somehow inside showColorbox(), is there a way for me to pass the onComplete param/code [via showColorbox(....{onComplete:yada yada}) or something] and have them relayed to the $.colorbox() function?

UPDATE: Ended up using the following successfully, added an extra objParams parameter to the showColorbox() function.

//m_title, m_url, m_width, m_height are from fixed parameters for showColorbox()        
var objBase = {title:m_title,href:m_url,width:m_width,height:m_height} ;
var objFinal = {};

//add base parameters passed in directly, fixed params
for(var item in objBase) {
    objFinal[item] = objBase[item];
}       
//add the parameters from objParams passed in (variable params/values)
for(var item in objParams) {
    objFinal[item] = objParams[item]
}   

//call function with combined parameters in object      
$.colorbox(objFinal)

None of the callers needed to be updated, but now passing in a new object using parameters which $.colorbox understands works fine! Thanks again!


It sounds like the solution you're looking for is wanting there to be a simple way to pass individual parameters of variable arguments as a named property value in an object literal. If so no there is no way to achieve this. Primarily because in this case there are no names for the arguments so there would be nothing for them to map to.

The best way to approach this problem altogether is to require an object at every stage and omit the extra parameters altogether.

function showColorbox(obj) {
  ...
  $.colorbox(obj);
}

showColorbox({title:title, href:url, width:width, height:height, opacity:0.7});


Why not just accept one parameter which is the object you pass to colorbox?

function showColorbox(params) {
    $.colorbox(params);
}

Then you can call it like this:

showColorbox({title:title, href:url, width:width, height:height, opacity:0.7});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜