Calling user control javascript functions from a new window (where the user controls are in the opener)
I have a user control which opens a new window for some item selection. Once an item is selected on that window, the item ID should be passed to a callback javascript function in the user control.
In order to have a unique callback function name in the user control (it may have multiple instances on the same page), I added the user control ID to the function name as follows (defined in the ascx file):
function开发者_运维问答 OnItemSelection_<%=this.ID%>(selectedItemID)
{
OnItemSelection("<%=SomeControl.ClientID%>", selectedItemID)
}
Where OnItemSelection is defined in an external js file:
function OnItemSelection(controlID, selectedItemID)
{
$(controlID).do_something(selectedItemID);
}
The issue is that now I'm not sure how the new page can call the "right" function (of the user control instance where it was opened from).
The only idea I have in mind so far is passing the name of the callback function in the query string:
var CallbackFunction = function(selectedItemID)
{
window.opener.<%=Request.QueryString["CallbackFunctionName"]%>(selectedItemID);
}
or maybe just the opening user control ID:
var CallbackFunction = function(selectedItemID)
{
window.opener.OnItemSelection_<%=Request.QueryString["UserControlID"]%>(selectedItemID);
}
My questions are:
1) Is it a bad practice passing javascript function names (or user control IDs) like that (I suspect it is)?
2) What could be better way to handle this scenario?
Edit:
Another way I'm considering now is declaring a global variable in the user control (registering it from the code behind so it'll appear only once). Then, when opening the new window, it's possible to assign the relevant function to it (OnItemSelection_<%=this.ID%>), and call it from the new window.
Seems much cleaner than passing user control data through the query string.
As I know the best practice in these situations is to open a modal window witch will return just an id with setting return value of window.
you can easily make decision using returned Id parameter (return value).
in parent Window :
var returnValue = window.showModalDialog("modalUrl.htm", "", sFeatures);
// use returned parameter
in modal Window :
window.returnValue = 12; //your Selected Item Id or etc
this is simple enough and also the most used practice.
精彩评论