At present, when I wish to display a dialog to a user, say to edit an object that’s been selected from the main window, I create a jQueryUI Dialog and insert an iframe inside of it to the page that handles the editing.
I’ve found this works very well because the dialog page can have its own scripts,styles, and element IDs. I don’t need to concern myself with any conflicts that could arise between my dialog and the parent page.
The only somewhat awkward part I’ve found is communication between the parent window and the child dialog. Unfortunately the child iframe usually needs to know about its parent. I’ve found this necessary so it can do things like closing its dialog (which resides in the parent window) or telling the parent to refresh its list of items after a successful edit.
Ideally the child wouldn’t be aware of its parent, but the benefits of a standalone page, that can be tested like any other with no conflicts seems worth it.
Still, I often read comments discouraging iframe use. I’m not sure if this is truly not a best practice, or some people simply prefer not to use them.
I’m always looking to improve the way I do things though. If using ajax for this type of thing really is best practice, how is it done for a non trivial dialog?
I can imagine using ajax to request the markup for a dialog and inserting that into the dialog, but I can’t figure out how to manage all of the conflicts, scripts, css, element IDs, etc for a complex dialog merging w/ an existing page.
Are there any examples of how this should be done? Or is iframe really better when your dialogs are not very simple?
Thanks for any ideas or help!
One thing you could do is use the namespace pattern so you do not have any conflicts in your scripts.
So you can have a namespaced object which contains all of your main page’s script to something like
MyApp.MainController
And similarly one for your dialog
MyApp.DialogController
As for making sure your jquery selectors do not collide (i.e. get all inputs just for the dialog instead of all of the inputs for the entire page) is to create a new namespaced object to contain the script for your dialog inside your main script and then pass in the dom context you want to scope your calls with. This is often done with javascript MVC pattern when constructing controllers
Inside your namespaced dialog script you can use delegates when creating your scripts and scope them appropriately.
This says “only bind events for input elements which live inside the ‘myScope'” element.
Finally for communication from your dialog to your main page you can use query triggers and trigger custom events on your scoped dialog element.
And in your main script you can listen for that event that was triggered