Online Book Reader

Home Category

AJAX In Action [96]

By Root 4071 0
displaying our information windows. Listing 5.4 showPopup() function and supporting code

var offset=8;

function showPopup(name,description){

var win=new ScriptIframePopup

(name,description,offset,offset,320,320);

offset+=32;

}

function ScriptIframePopup(name,description,x,y,w,h){

var bod=document.createElement("div");

document.body.appendChild(bod);

this.contentDiv=document.createElement("div");

this.contentDiv.className="winContents";

this.contentDiv.innerHTML=description;

bod.appendChild(this.contentDiv);

this.win=new windows.Window(bod,name,x,y,w,h);

}

Licensed to jonathan zheng

184

CHAPTER 5

The role of the server

We define a function showPopup that takes a name and description as argument and constructs a window object for us. Listing 5.5 shows an example script that invokes this function.

Listing 5.5 script_earth.js

var name='earth';

var description="A small blue planet near the outer rim of the galaxy,"

+"third planet out from a middle-sized sun.";

showPopup (name,description);

We simply define the arguments and make a call against the API. Behind the scenes, though, we need to load this script from the server and persuade the browser to execute it. There are two quite different routes that we can take. Let’s examine each in turn.

Loading scripts into IFrames

If we load a JavaScript using an HTML document

When we try to load this code, it doesn’t work, because the IFrame creates its own JavaScript context and can’t directly see the API that we defined in the main document. When our script states showPopup(name,description);

the browser looks for a function showPopup() defined inside the IFrame’s context. In a simple two-context situation such as this, we can preface API calls with top, that is,

top. showPopup(name,description);

in order to refer to the top-level document. If we were nesting IFrames inside IFrames, or wanted to be able to run our application inside a frameset, things could get much more complicated.

The script that we load uses a functional approach. If we choose to instantiate an object in our IFrame script, we will encounter further complications. Let’s say that we have a file PlanetInfo.js that defines a PlanetInfo type of object that we invoke in our script as

var pinfo=new PlanetInfo(name,description);

To use this type in our script, we could import PlanetInfo.js into the IFrame context, by adding an extra script tag:

The PlanetInfo object created within the IFrame would have identical behavior to one created in the top-level frame, but the two wouldn’t have the same prototype. If the IFrame were later destroyed, but the top-level document kept a reference to an object created by that IFrame, subsequent calls to the object’s methods would fail. Further,

Return Main Page Previous Page Next Page

®Online Book Reader