[Contents] [Previous] [Next] [Index]

## Chapter 2
Creating JavaScript Components

This document describes how to create, package, and import JavaScript components into Visual JavaScript (VJS) for use as application building blocks. The concept of JavaScript "components" is unique to VJS, and entails describing the properties, methods, and events for the component in a special file, called a JavaScript Bean (JSB) file. This document describes how to define a JavaScript component, and its properties, methods, and events, in a JSB file.

Sections in this document include the following topics:

- What is a JavaScript Component?
- Requirements for Creating JavaScript Components
- Understanding JavaScript Components
- Creating a JavaScript Component
- JavaScript Component Examples

## What is a JavaScript Component?

Visual JavaScript lets you use components from several different sources to build your Visual JavaScript applications. One of those sources is JavaScript. Visual JavaScript, supports the creation of special, SGML-based text files, called JavaScript Bean (JSB) files, each of which define the properties, events, and methods for a component, and that encapsulate the JavaScript constructor function necessary to create and reuse a JavaScript component, and to display its properties, events, and methods in the Visual JavaScript inspector.

The JSB file structure is modeled on the Java BeanInfo class for Java components. Each JSB file describes the properties, events, methods of a single component. It also describes one or more listener interfaces, which are used to process events, especially when the events are managed by other objects. Finally, each JSB file also contains a constructor function, which creates the component and defines its behavior at run time.

After you create a JSB file, you install the component on the Visual JavaScript palette for use. If a component uses other files for support (such as JavaScript files or Java classes), then before you can install it on the palette, you must package the component into a JAR file, and install the JAR to the palette. Once a JavaScript component is installed on the palette you can use it without being concerned about its source (you can always examine the source for the component by choosing View |Source from the Visual JavaScript menu).

You can develop client-side and server-side JavaScript components, and you can develop components that can run on either the client or server, or that run on both the client and server as needed. You can also develop components that make use of external Java objects to handle events. This document describes how to create these JavaScript components, and how to deploy them on the Visual JavaScript palette so you can use them to build applications for your end users.

## Requirements for Creating JavaScript Components

To create JavaScript components you should be familiar with Visual JavaScript, the JavaScript language, and the general principles of object-based programming. In particular, you should know how to use Visual JavaScript to create applications, and you should understand the types of connections used by Visual JavaScript. If you plan to create server-side components, you should also be familiar with server-side JavaScript and LiveWire.

To create JavaScript components, you must have a text editor, and Visual JavaScript installed on your machine. If you create multifile components, you also need the Sun Java Developer's Kit (JDK) 1.1 JAR packager. To test client-side components, you must also have Netscape Navigator 3.02 or Netscape Communicator 4.xx. To test server-side components, you must have Netscape Enterprise Server 2.0 or 3.x.

> NOTE: On Windows platforms, the CDK ships with the Acadia JavaScript BeanBuilder which you can also use to create JS components. The Acadia JavaScript BeanBuilder is not described in this document, but it and its supporting documentation is delivered as part of the CDK.

## Understanding JavaScript Components

In JavaScript, components are implemented as custom JavaScript objects. In JavaScript you can define an object and its properties and methods using a constructor function, and then create instances of the object with the new operator. For example, the following script fragment defines the my_person_obj, and then creates two instances of the my_person_obj object:

    function print_person() {
       // The "this.name" notation in the next line references the "name"
       //property of the object this method was called from
       document.write(this.name + " is " + this.age + " years old")
    }
    function my_person_obj(name, age) {
       this.name = name // Set the "name" property
       this.age = age // Set the "age" property
       this.print = print_person // Specify the "print_person" method
    }
    person1 = new my_person_obj("Walter", 54)
    person2 = new my_person_obj("Betty", 35)

Once you instantiate a custom object, you can access its properties and methods using the same notation you use for built-in JavaScript objects, such as document and window. For example:

    person1_age = person1.age  // read a value from a property
    person2.name = person2_name  // set a property value
    person1.print()  // call a method

JavaScript is, however, an instance-based object model. Unlike Java, JavaScript does not have classes, inheritance, or a built-in component model. Visual JavaScript, however, provides the JSB files as a mechanism for creating a custom JavaScript component once, packaging it, and installing it on a Visual JavaScript palette where you can use it in any Visual JavaScript application merely by dragging it to the application and optionally setting its property values in the inspector.

A JSB file is an SGML-based text file that formalizes the definition of a custom JavaScript object so that it can be used in different applications without requiring you to recreate it over and over again. The JSB file defines the properties, events, and methods for a component, and encapsulates the JavaScript constructor function necessary to create a JavaScript component.

As previously noted, the JSB file structure is modeled on the Java BeanInfo class for Java components. If you know and understand the BeanInfo class, then you already know much about the JSB file structure. A JSB file also contains additional information, specific to Visual JavaScript, that is not in a BeanInfo.

For example, the following text illustrates how the JavaScript my_person_obj describes above might partially appear in a JSB file:

    <JSB>
       <JSB_DESCRIPTOR NAME="my_person_obj">
       <JSB_PROPERTY NAME="name" TYPE="string">
       <JSB_PROPERTY NAME="age" TYPE="string">
       <JSB_METHOD NAME="print" TYPE="void"> </JSB_METHOD>
       <JSB_CONSTRUCTOR>
          function print_person() {
             document.write(this.name + " is " + this.age + " years old")
          }
          function my_person_obj(params) {
             this.name = params.name      // Set the "name" property
             this.age = params.age        // Set the "age" property
             this.print = print_person    // Set the "print_person" method
          }
       </JSB_CONSTRUCTOR>
    </JSB>

As this example illustrates, a JSB file describes a single component in terms of its properties, and methods. The JSB file also contains a constructor function, which is the JavaScript source of the component.

> NOTE: The my_person_obj does not have any events associated with it, but if it did, they would also be described in the JSB file with <JSB_EVENT> tags. For each event there would also be a corresponding listener interface (<JSB_LISTENER>). Listener interfaces process events, especially when those events are managed by other objects.

## Creating a JavaScript Component

Creating a JavaScript component for Visual JavaScript is an iterative, three-step process:

1. Creating a JSB File for a Component.

2. Packaging a Component into a JAR file. Note that this step is only required for multifile JavaScript components, such as those that use supporting JavaScript functions or Java classes located in other files.

3. Loading and Testing a Component.You install components into Visual JavaScript using Tools | Install to Palette | JavaScript Component.

### Creating a JSB File for a Component

To define a reusable JavaScript component for Visual JavaScript, you must create a JSB file that defines the component's properties, events, methods, constructor function, and listener interfaces. You can create a JSB file using any text editor.

> NOTE: You can also use Acadia JavaScript BeanBuilder to create JavaScript components. BeanBuilder ships with the CDK, and is available only on Windows platforms.

A JSB file consists of text tags that encapsulate a single component definition. The file format is plain text that can be parsed according to SGML rules. Tags are enclosed in angle brackets, and can be nested as appropriate. A component definition in a JSB file is enclosed by a <JSB> and </JSB> tag pair. Within this pair, are embedded tags that define meta information for the component. For example, all components defined in a JSB file have tags that define:

- Properties for the object. Depending on the component, some properties can be queried and set directly. Others require Get and Set methods. Properties are defined in a JSB file using property descriptors.

- Methods for the object, and parameters for the method. Methods are defined in a JSB file using method descriptors.

- Events to which scripts can be assigned, and which are evaluated by JavaScript when the trigger condition occurs. Events are defined in a JSB file using event set descriptors

- Listener interfaces, which are used to process events. There is typically one listener interface for each event.

- A constructor, that initializes the component and contains the actual code for the component's methods and events.

Typically, a skeleton JSB file looks like this:

    <JSB>
       <JSB_DESCRIPTOR ...>
       <JSB_PROPERTY ...>
       ...
       <JSB_EVENT ...>
       ...
       <JSB_METHOD ...>
       ...
          <JSB_PARAMETER>
          ...
       </JSB_METHOD>
       ...
       <JSB_CONSTRUCTOR ...> </JSB_CONSTRUCTOR>
    </JSB>

Depending on a component's event definitions, the JSB file usually also contains interface definitions that enable handling a component's events through an external object, such as another Java component. Interface definitions follow a component's definition. Each interface definition is placed within <JSB_LISTENER> and
</JSB_LISTENER> tags:

    ...
    </JSB>

    <JSB_LISTENER ...> </JSB_LISTENER>
    ...

For example, here is the contents of the MailToLink JSB file. This is a very simple JavaScript component. For more examples, look at the JSB files provided as part of the CDK.

    <JSB>

    <JSB_DESCRIPTOR NAME="netscape.sample.MailToLink" ENV="client"
       DISPLAYNAME="MailTo Link"
       SHORTDESCRIPTION="E-mail Hyperlink">

    <JSB_PROPERTY NAME="to" PROPTYPE="JS" TYPE="string"
       DISPLAYNAME="addressee (to)"
       SHORTDESCRIPTION="Comma-separated list of addressees">

    <JSB_PROPERTY NAME="cc" PROPTYPE="JS" TYPE="string"
       DISPLAYNAME="copies (cc)"
       SHORTDESCRIPTION="Comma-separated list of addressees">

    <JSB_PROPERTY NAME="bcc" PROPTYPE="JS" TYPE="string"
       DISPLAYNAME="blind copies(bcc)"
       SHORTDESCRIPTION="Comma-separated list of invisible addressees">

    <JSB_PROPERTY NAME="subject" PROPTYPE="JS" TYPE="string"
       DISPLAYNAME="Subject"
       SHORTDESCRIPTION="Subject of message">

    <JSB_PROPERTY NAME="text" PROPTYPE="JS" TYPE="string"
       DISPLAYNAME="Link text"
       SHORTDESCRIPTION="Text displayed in link">

    <JSB_EVENT NAME="onclick" EVENTMODEL="HTML"
       LISTENERTYPE="onClickListener"
       LISTENERMETHODS="onClick">

    <JSB_METHOD NAME="onclick"> </JSB_METHOD>

    <JSB_CONSTRUCTOR>
       function netscape_peas_MailToLink(params) {
          str = "<A HREF='mailto:" + params.to + "?subject=" +
             params.subject + "&cc=" + params.cc + "&bcc=" +
             params.bcc + "' ONCLICK ='" + params.onclick + "'>" +
             params.text + "</A>"
          document.write(str)
       }
    </JSB_CONSTRUCTOR>

    </JSB>

    <JSB_LISTENER NAME="onClickListener"
       <JSB_METHOD NAME="onClick" TYPE="java.lang.Void"
    </JSB_LISTENER>

For a complete description of the structure of a JSB file and a reference to the tags in can contain, see "JSB File Structure Reference".

#### Creating Properties for a Component

A JavaScript component can have zero or more public properties. A property is essentially a public data member of the component. Creating a property is a two-step process:

1. Add a <JSB_PROPERTY> tag to the JSB file. The tag that defines the name, property type, and data type of the property.

2. Assign the property to the component object in the constructor function. Often, the constructor also uses the property in some manner at run time.

Properties are defined in a JSB file using the <JSB_PROPERTY> tag. At a minimum, a property definition has the following attributes:

- NAME, which specifies a unique name for the property in this component.

- PROPTYPE, which specifies how a property's value is bound.

- TYPE, which indicates the data type of the property. This can be a JavaScript data type, or a fully-qualified Java class.

For a full description of the <JSB_PROPERTY> tag and its attributes, see "<JSB_PROPERTY>".

After you define a property in a property tag, you must assign it to the component object in the constructor function for the component. If you expect other components will access the object's properties at run time, you can also, optionally, initialize the property values in the constructor. If you do not, you should initialize them in the Visual JavaScript inspector. The constructor function is wrapped by the <JSB_CONSTRUCTOR> tag. For information about creating a constructor function, see "Defining a Constructor Function".

Depending on how a property is declared in a JSB file, it can be accessed by other components on a page in one of two ways:

- Directly, using the syntax <objectid>.<property name>. This is the default access method.

- Indirectly, through Get and Set methods that you specify with the READMETHOD and WRITEMETHOD attributes, respectively. If specified, you must also create matching method definitions using <JSB_METHOD> tags.

For example, Visual JavaScript accesses a component property when a property connection is made from one component to another. In this case, the property on the target component is set using a write method, if one exists, or the syntax <object id>.<property name> = XXXX if a write method is not specified.

Assigning values for some properties only makes sense at run time. For example, the property that stores the current row number in a table, cannot be set at design time when a table is not being accessed. To designate a property that is set only at run time, specify the ISRUNTIME attribute when defining the property.

Visual JavaScript uses property definitions to construct an instance of a component. For example, if a component is defined with three properties named prop_a, prop_b, and prop_c, then Visual JavaScript automatically generates the following script for the component:

    var params = new JSObject()
    params.prop_a = "value user entered for a"
    params.prop_b = "value user entered for b"
    params.prop_c = "value user entered for c"
    params.id = "MyComp1"
    MyComp1 = new com_xxx_MyComp( params )

##### Creating Properties With Read/Write Methods

JavaScript component properties are read and written using the standard JavaScript "dot" notation syntax:

    some_variable = my_obj.property
    my_obj.property = some_other_variable

There are times, however, when it would be better to set a property set through a method call rather than directly. This can be accomplished by defining a write-method for the property. In other situations, you might want to have a property's value read through a method call rather than directly. For example, this would be useful when the property value is calculated based upon other inputs, or when it is a constantly changing value outside the control of the component, such as a cursor position. In these cases, a read-method can be defined for the property, so that the property value can be correctly calculated and returned. You might also prefer to use read and write methods to trigger an event when a property's value changes.

Defining a read or write method for a property is a two-step process:

1. Add a READMETHOD or WRITEMETHOD attribute to the property's <JSB_PROPERTY> tag.

2. Create the named read or write methods.

The READMETHOD and WRITEMETHOD attributes should be set to the name of the methods which implement the read and/or write-methods for the property.

For example, here is a definition for a "msg" property, which contains a WRITEMETHOD attribute:

    <JSB_PROPERTY NAME="msg" TYPE="java.lang.String"
       PROPTYPE="JS"
    WRITEMETHOD="setMsg"
    ISBOUND
    DISPLAYNAME="Message"
    SHORTDESCRIPTION="Text message to scroll in status bar">

The read and write methods are themselves defined using the <JSB_METHOD> tags as illustrated above. The signatures of the functions should adhere to the following pattern, assuming the property type is java.lang.XXX:

    READMETHOD: java.lang.XXX <read-method>()

    WRITEMETHOD: java.lang.Void <write-method>(java.lang.XXX)

Read methods must always be prefaced with "get" and write methods must always be prefaced with "set". For example

    getMsg()
    setMsg()

##### Making a Property the Source of a Property Connection

Allow a property to become the source of a property connection is a two-step process:

1. Mark the property as a bound property

2. Create and fire an onChange event whenever the property value should be propagated

When a property is marked bound, it means that the value of that property may be bound to the property of another component. It is an indication that an onChange event will be fired whenever the value of the property has changed or needs to be propagated.

To mark a property as bound, add the ISBOUND attribute to the property's <JSB_PROPERTY> tag. For example:

    <JSB_PROPERTY NAME="msg" TYPE="java.lang.String"
    PROPTYPE="JS"
    WRITEMETHOD="setMsg"
    ISBOUND
    DISPLAYNAME="Message"
    SHORTDESCRIPTION="Text message to scroll in status bar">

Whenever the value for a bound property changes, the component must call an onChange event, defined as follows:

    <JSB>

    ...

    <JSB_EVENT NAME="onChange" EVENTMODEL="JS"
       LISTENERTYPE="onChangeListener"
       LISTENERMETHODS="onChange">

    ...

    </JSB>
    <JSB_LISTENER NAME="onChangeListener">
       <JSB_METHOD NAME="onChange" TYPE="java.lang.Void">
          <JSB_PARAMETER NAME="propertyName" TYPE="java.lang.String">
          <JSB_PARAMETER NAME="oldValue" TYPE="java.lang.String">
          <JSB_PARAMETER NAME="newValue" TYPE="java.lang.String"><
       </JSB_METHOD>
    </JSB_LISTENER>

As this code illustrates, the onChange event method takes three parameters:

1. The name of the property whose value is being propagated

2. The old value of the property

3. The new value of the property

#### Creating Methods for a Component

A JavaScript component can have zero or more public methods. Methods provide a way for other components to modify or control the behavior of the component through a defined interface. Methods are defined in <JSB_METHOD> tags, and implemented in the <JSB_CONSTRUCTOR>.

Adding a method to a component is a two-step process

1. Create the method definition using the <JSB_METHOD> tag. If the method takes parameters, embed each parameter definition in the method definition using <JSB_PARAMETER> tags.

2. Script the method function, and assign the function as a property in the component's constructor.

A method definition must specify the method name. If a method returns a value, the method definition must specify the data type of the return value using the TYPE attribute. A method that takes parameters also contains embedded parameter definitions. For example, here is a method definition for a method that returns a value, and takes three parameters:

    <JSB_METHOD NAME="directionChange" TYPE="java.lang.String">
       <JSB_PARAMETER NAME="propertyName" TYPE="java.lang.String">
       <JSB_PARAMETER NAME="oldValue" TYPE="java.lang.String">
       <JSB_PARAMETER NAME="newValue" TYPE="java.lang.String">
    </JSB_METHOD>

This method returns a Java string data type. Each of its parameters is also a Java string data type. Return values and parameters can be based on Java classes, as in this example,. or they can be JavaScript data types.

For a full description of the <JSB_METHOD> tag and its attributes, see "<JSB_METHOD> </JSB_METHOD>". For a complete description of parameter tags, see "<JSB_PARAMETER>".

The method function is the actual JavaScript function that implements the named method. There are no restrictions on the name of the function, as long as it is uniquely named on the page. To avoid naming conflicts, it is strongly recommended that the name of the method function match the name of the component itself, with a unique prefix or suffix attached. The method's signature must match the signature defined by the corresponding <JSB_METHOD> tags.

> Tip To view the methods associated with a component at design-time, put a temporary button on a page, make a connection from the button to the component whose methods you want to examine, and choose View Parameters on the button. The Action dropdown lists the methods of the component. Select a method from the list to see it parameters.

The script between the JSB_CONSTRUCTOR tags must define all the functions, including the constructor function. The constructor function must assign the other functions to appropriate property. For example, a class that includes the methods "next" and "previous" would define JSB_METHOD tags for these functions, embedding parameter tags as necessary, and the constructor script would implement the methods as follows:

    <JSB_CONSTRUCTOR>

       function com_xxx_MyComp_next() {
          //put code here
       }

       function com_xxx_MyComp_previous() {
          //put code here
       }

       function com_xxx_MyComp( params ) {
          this.next = com_xxx_MyComp_next
          this.previous = com_xxx_MyComp_previous
       }

    </JSB_CONSTRUCTOR>

Methods have access to all of a component's properties defined in the JSB file.

> NOTE: If the JSB file is actually a wrapper for a non-JavaScript component (e.g., a JavaBean component), and not all of the component's actually properties are defined in the JSB file, methods also have access to those "private" properties not exposed in the JSB file.

#### Creating Events for a Component

Properties and methods allow your component to interact with other components. Other components can read and write your properties and call your methods, but not the other way around.

You can, however, denote events and create events handlers for your components that can respond to specific application events. An event is something that happens in the application, often as the result of a user action, such as clicking a button. An event handler is a function (and corresponding method definition) that is triggered when the event occurs, such as onClick.

Adding an event to a component is a three-step process:

- Define the event and its listener interface

- Define the event function that is called when the event is triggered.

- Trigger the event function from your constructor and methods when appropriate

A JavaScript component can be defined as the source of zero or more events. An event is a component-defined trigger that can be used to initiate application activities. They are analogous to the JavaScript events produced by HTML objects, such as the onChange and onFocus events produced by text fields, but they represent component-specific conditions. Events are defined in a JSB file using the <JSB_EVENT> tag. Events must be defined with a unique NAME attribute. For a full description of the <JSB_EVENT> tag and its attributes, see "<JSB_EVENT>". For example:

    <JSB_EVENT NAME="directionChange" EVENTMODEL="JS"
       LISTENERTYPE="directionChangeListener"
       LISTENERMETHODS="directionChange">

Event definitions must also specify the EVENTMODEL attribute, which indicates to Visual JavaScript how it should connect components at run time in response to the triggering of the event. EVENTMODEL can be "JS" indicating a JavaScript event model where Visual JavaScript creates an event method on the fly, "AWT11" for events that use listener methods to connect components, or "HTML", as in the MailToLink example described earlier in this document. Components that define events that use the JavaBean event model interface, must also define listener methods using the <JSB_LISTENER> tag. To learn about defining the listener interface, see "Creating a Listener Interface for a Component".

If the EVENTMODEL is JS, then Visual JavaScript generates the function whenever the user makes a connection to that event, and it assigns the function to the object as a method. Multicasting is supported because the generated function can contain any number of resulting function calls. The component developer needs only call this function whenever the conditions exist that the event should be fired. For example, suppose a component defines an event called "onRowChange" that is triggered every time a row in a database table changes, which happens anytime a next() or previous() function is called. The constructor script might look like this:

    <JSB_CONSTRUCTOR>
       function com_xxx_MyComp_next() {
          . . .
          this.onRowChange(0,0,0)
       }
       function com_xxx_MyComp_previous() {
          . . .
          this.onRowChange(0,0,0)
    }
       function com_xxx_MyComp( params ) {
          this.next = com_xxx_MyComp_next
          this.previous = com_xxx_MyComp_previous
       }
    </JSB_CONSTRUCTOR>

> NOTE: Events allow a component to be the source for event and property connections. A special event, named onChange, must be implemented for a component to be the source for property connections, as this is the trigger that is used to indicate that a property value has changed.

#### Creating a Listener Interface for a Component

One goal of Visual JavaScript is to allow the seamless interaction between Java Beans and JavaScript components. Java Beans have a very specific mechanism for the firing and receiving of events based around the concept of event producers and event listeners. To allow for the future integration of JavaScript and Java components, events produced by JavaScript components are defined using the same producer/listener concept.

In Java Beans, event propagation works as follow:

- A source component that will trigger an event specifies a listener interface that defines the name and signature of the event method used to process the event.

- A target component that should receive an event registers as an event listener with the source component that fires the event. It also implements the event method defined by the source component's listener interface. That event method processes the event.

- When the source component fires the event, it calls its pre-defined event method on each of the registered listeners.

Because Java is a strongly-typed language, the compiler can detect whether a component has implemented the correct interface to be the listener for a particular event. JavaScript is dynamically typed, so it is up to Visual JavaScript to make certain that event producers and event listeners are properly matched. The information Visual JavaScript needs to do this is specified in the JSB in the form of <JSB_EVENT> and <JSB_LISTENER> tags.

For example, consider the following <JSB_EVENT> and <JSB_LISTENER> definitions.

    <JSB>

    . . .

    <JSB_EVENT NAME="directionChange" EVENTMODEL="JS"
       LISTENERTYPE="directionChangeListener"
       LISTENERMETHODS="directionChange">

    . . .

    </JSB>

    <JSB_LISTENER NAME="directionChangeListener">
       <JSB_METHOD NAME="directionChange" TYPE="java.lang.Void">
          <JSB_PARAMETER NAME="propertyName" TYPE="java.lang.String">
          <JSB_PARAMETER NAME="oldValue" TYPE="java.lang.String">
          <JSB_PARAMETER NAME="newValue" TYPE="java.lang.String">
       </JSB_METHOD>
    </JSB_LISTENER>

The <JSB_EVENT> tag defines the event name, listener interface name and event method name of the event that occurs. The <JSB_LISTENER> tag is used to define the listener interface itself. It specifies the name of the listener interfaces, and always surrounds one or more <JSB_METHOD> tags that define the event methods within the interface. For more information about defining methods, see "Creating Methods for a Component".

Note that the <JSB_LISTENER> tag is contained outside of the <JSB> tag, at the top level of the JSB file. <JSB_LISTENER> is the only tag that is placed outside the scope of the <JSB> tag. The reason for this is to make the definition more like a Java Bean, where the listener interface would normally be created in a file separate from the BeanInfo.

#### Defining a Constructor Function

A JavaScript constructor function creates a new JavaScript object, either in the client or server environment. The name of the constructor function for a JavaScript component is the same as the name of the component in the <JSB_DESCRIPTOR> tag, except that package names are separated by underscores instead of periods. For example, the MailToLink constructor function is named netscape_peas_MailToLink, because it is in the netscape.peas package.

By convention, a constructor function takes a single argument that is a JavaScript object with properties that correspond to the component's properties as specified in the JSB. For example, here is the constructor function for MailToLink, a client component that creates a hyperlink to pop up a mail composition window:

    function netscape_peas_MailToLink(params) {
       str = "<A HREF='mailto:" + params.to + "?subject=" +
          params.subject + "&cc=" + para "&bcc=" +
          params.bcc + "` ONCLICK ='" + params.onclick + "`>" +
          params.text + "</A>
       document.write(str)
    }

Visual JavaScript automatically embeds the constructor function within the <SCRIPT> or <SERVER> tags, depending on whether a component runs on the client or the server, respectively.

Normally, the constructor function gets the property values based on what the user enters in the VJS Inspector. You should always initialize the value of a component's properties in the constructor function to prevent errors if another object attempts to retrieve property values from your component and the property values are not already set. The constructor function is called when an instance of the component is placed on the page. Visual JavaScript sets the properties of each instance using the settings of the object passed as an argument to the constructor call, for example:

    _params_ = new Object();
    _params_.to = "you@wherever.com";
    _params_.subject = "Something Very Important";
    _params_.cc = "foo@bar.com";
    _params_.bcc = "";
    _params_.onclick = "";
    link1 = new netscape_peas_MailToLink(_params);

This code is generated by Visual JavaScript.

A constructor function may return an object or not, depending on its purpose. The example MailToLink component creates a result string and writes out HTML. Constructor functions for other JavaScript components may return an object as well as t generating output.

#### Improving Application Speed with Smaller Constructors

At run time, the constructor code contained in a JSB file is duplicated on every application page that uses the component. If your constructor script is large, you can improve application performance by moving most of the script to a separate .JS file, and creating a constructor that writes out the HTML to include the script. For example,

    <JSB_CONSTRUCTOR>
       .
       .
       .
       document.write("<SCRIPT SRC=myfile.js><\/SCRIPT>");
       .
       .
       .
    </JSB_CONSTRUCTOR>

Using this technique, the .JS file is still read for every page that uses the component, but after the first page, the script is read from the browser's cache rather than being downloaded again.

> NOTE: If you use this technique, be sure to put both the JSB and .JS files into a JAR file before importing the component to the palette. Using a JAR file to package the component and its supporting script file ensures that the FILEREFS attribute for the component includes the supporting file when you deploy your application.

### Packaging the JSB file into a JAR file

You must create a JAR (Java archive) file for JavaScript components only if they comprise more than one file. For example, if a JavaScript component or its constructor or helper methods make use of functions you have defined in external JavaScript (.JS) files on the client- or server-sides, you must package the component and its supporting files in a JAR file prior to import. Otherwise, creating a JAR file for a component is optional. Putting a component and its supporting files, if any, in a JAR file enables Visual JavaScript to import them when the component is imported to the palette, and to deploy them when a project is deployed.

To create a JAR file, you need the Java Developer's Kit (JDK) version 1.1. Ordinarily, at least one of the files you put into a JAR file must be a JavaBean as defined in the JDK 1.0.2 transitional bean specification. A JavaScript component is considered a JavaBean for purposes of JAR file construction.

For a complete set of instructions for packaging a JSB and its supporting files into a JAR file, see Packaging a Component.

### Loading and Testing a Component

Once you package a JavaScript component into a JAR file, you can easily load the component into a Visual JavaScript palette for testing, debugging, and use:

1. Select or create the Visual JavaScript palette into which to load the component.

2. Choose Tools | Install to Palette | New.

3. Select the JAR file containing your component in the file selector.

Your component should now appear as an icon on the palette, where you can test and debug it. Typically, you will fix and refine your component a number of times before you consider it ready for production use. While you can make changes to the original JSB file, repackage it into a new JAR file, and load the new version of the component into Visual JavaScript, you can also avoid repackaging and reloading by following these steps:

1. Locate your JSB file under the Visual JavaScript install directory. It is located in a sub-directory tree named after the component's package name, off the install directory. For example, if your component exists in the acme.components package, the component's JSB will be located in the directory <INSTALLROOT>/acme/components.

2. Edit the JSB file directly under the Visual JavaScript install directory.

3. Restart Visual JavaScript after each revision.

## JavaScript Component Examples

Visual JavaScript contains ready-made JavaScript components that you can study and use. The JSB files for the JavaScript components packaged with Visual JavaScript are included in the CDK.

[Contents] [Previous] [Next] [Index]

Last Updated: 09/08/97 15:35:14

Copyright © 1997 Netscape Communications Corporation