View
Module | ejs.web |
Definition | dynamic class View |
Inheritance | View ![]() |
Specified | ejscript-2.5 |
Stability | Prototype. |
Base class for web framework Views.
This class provides the core functionality for templated Ejscript view web pages. Ejscript web pages are compiled to create a new View class which extends the View base class. This class provides a suite of high-level control methods that generate HTML for input, output and presentation needs. In addition to the properties defined by this class, user view classes will typically inherit at runtime, all public properites of any associated controller object defined in Request.controller.
Control Methods
Control methods are grouped into two families: input form controls and general output controls. Input controls are typically located inside a form/endform control pair that defines a current data record from which data will be presented. Output controls can be used anywhere on a page.Input controls are generally of the form: function(field, options) where field is the name of the property in the current record that contains the data to display. The options is an object hash that controls and modifies how the control will render. The options hash can also be a plain string, in which case it is interpreted as an object hash with a single "action" property set to the value of the options string. i.e. {action: options}. Note that controls will modify the options object and so sharing one option set over many controls is not advisable.
Various controls have custom options, but most share the following common set of option properties.
Properties
Qualifiers | Property | Type | Description |
---|---|---|---|
config | Object | null | |
controller | Optional controller object. | ||
formats | Object | null | |
formatters | null | ||
params | Object | Form and query parameters - reference to the Request.params object. | |
request | Object | Current request object. | |
get | session | Session | Session state object. The session state object can be used to share state between requests. If a session has not already been created, accessing this property automatically creates a new session and sets the Request.sessionID property and a cookie containing a session ID sent to the client with the response. To test if a session has been created, test the sessionID property which will not auto-create a session. Objects are stored in the session state using JSON serialization. |
View Class Methods
Qualifiers | Method |
---|
View Instance Methods
Qualifiers | Method |
---|---|
View(request: Object) | |
Constructor method to initialize a new View. | |
alert(text: String, options: Object = expression): Void | |
Emit a status alert area TODO - review?. | |
anchor(text: String, options: Object = expression): Void | |
Emit an anchor. | |
button(name: String, label: String, options: Object = expression): Void | |
Render a form button. | |
buttonLink(text: String, options: Object = expression): Void | |
Render a link button. | |
chart(data: Array, options: Object = expression): Void | |
Render a chart. | |
checkbox(name: String, checkedValue: Object = true, options: Object = expression): Void | |
Render an input checkbox. | |
currency(fmt: String): String | |
Temporary helper function to format a number as currency. | |
div(body: String, options: Object = expression): Void | |
Render a HTML division. | |
endform(): Void | |
End an input form. | |
flash(kinds: Object = null, options: Object = expression): Void | |
Emit a flash message area. | |
form(record: Object, options: Object = expression): Void | |
Render a form. | |
icon(src: Object, options: Object = expression): Void | |
Emit an icon link. | |
image(src: String, options: Object = expression): Void | |
Render an image. | |
input(name: String, options: Object = expression): Void | |
Render an input field as part of a form. | |
label(text: String, options: Object = expression): Void | |
Render a text label field. | |
list(name: String, choices: Object, options: Object = expression): Void | |
Emit a selection list. | |
mail(name: String, address: String, options: Object = expression): Void | |
Emit a mail link. | |
number(fmt: String): String | |
Temporary helper function to format a number. | |
progress(percent: Number, options: Object = expression): Void | |
Emit a progress bar. | |
date(fmt: String): String | |
Temporary helper function to format the date. | |
formatValue(value: Object, options: Object): String | |
Get the data value for presentation. | |
link(target: Object): Uri | |
Create a URI link. | |
radio(name: String, choices: Object, options: Object = expression): Void | |
Render a radio button. | |
redirect(target: Object, status: Number): Void | |
Redirect the client to a new URL. | |
render(renderer: Function): Void | |
Process and emit a view to the client. | |
script(target: Object, options: Object = expression): Void | |
Emit a script link. | |
securityToken(options: Object = expression): Void | |
Generate a security token for the page and emit a <meta HTML element for the security token. | |
setHeader(key: String, value: String, overwrite: Boolean): Void | |
Convenience routine to set a Http response header in responseHeaders. | |
setHeaders(headers: Object, overwrite: Boolean): Void | |
Convenience routine to set multiple Http response headers in responseHeaders. | |
setStatus(status: Number): Void | |
Convenience routine to set the (proposed) Http response status code. | |
table(data, options: Object = expression): Void | |
Render a table. | |
stylesheet(target: Object, options: Object = expression): Void | |
Emit a style sheet link. | |
tabs(data: Object, options: Object = expression): Void | |
Render a tab control. | |
text(name: String, options: Object = expression): Void | |
Render a text input field as part of a form. | |
tree(data: Object, options: Object = expression): Void | |
Render a tree control. | |
view(viewPath, options: Object = expression): Void | |
Render a partial view. | |
write(data: Array): Number | |
Write data to the stream.Write data to the client. | |
writeSafe(data: Array): Number | |
Write safely. |
Method Detail
ejs.web View(request: Object)
- Description
- Constructor method to initialize a new View.
- Parameters
request: Object Request object.
- Description
- Emit a status alert area TODO - review?.
- Parameters
text: String Initial message text to display. Status messages may be updated by calling the Controller.status function. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
period Polling period in milliseconds for the client to check the server for status message updates. If this is not specifed, the connection to the server will be kept open. This permits the server to "push" alerts to the console, but will consume a connection at the server for each client.
- Example
<% alert("Status Message", { refresh: "/getData", period: 2000" }) %>
- Description
- Render a form button. This creates a button suitable for use inside an input form. When the button is clicked, the input form will be submitted.
- Parameters
name: String Name for the input button. This defines the HTML element name and provides the source of the initial value to display. label: String Text label to display in the button and value to send when the form is submitted. options: Object Optional extra options. See View for a list of the standard options. Examples: button("commit", "OK") button("commit", "Cancel") X. [default: expression]
- Description
- Render a link button. This creates a button suitable for use outside an input form. When the button is clicked, the associated URI will be invoked.
- Parameters
text: String Text to display in the button. The text can contain embedded HTML. options: Object Options specifying the target URI to invoke. See View for a list of the standard options. [default: expression]
- Example
buttonLink("Cancel", "\@")
- Description
- Render a chart. The chart control can display static or dynamic tabular data. The client chart control manages sorting by column, dynamic data refreshes, pagination and clicking on rows. TODO -- update.
- Parameters
data: Array Optional initial data for the control. The data option may be used with the refresh option to dynamically refresh the data. options: Object Object Optional extra options. See also View for a list of the standard options. [default: expression]
- Options
columns Object hash of column entries. Each column entry is in-turn an object hash of options. If unset, all columns are displayed using defaults. kind String Type of chart. Select from: piechart, table, linechart, annotatedtimeline, guage, map, motionchart, areachart, intensitymap, imageareachart, barchart, imagebarchart, bioheatmap, columnchart, linechart, imagelinechart, imagepiechart, scatterchart (and more).
- Example
<% chart(grid, { refresh: "/getData", period: 2000" }) %> <% chart(data, { click: "\@update" }) %>
- Description
- Render an input checkbox. This creates a checkbox suitable for use within an input form.
- Parameters
name: String Name for the input checkbox. This defines the HTML element name and provides the source of the initial value for the checkbox. The field should be a property of the form control record. It can be a simple property of the record or it can have multiple parts, such as: field.field.field. If this call is used without a form control record, the actual data value should be supplied via the options.value property. checkedValue: Object Value for which the checkbox will be checked. Defaults to true. [default: true] options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Description
- Temporary helper function to format a number as currency. TODO.
- Parameters
fmt: String Format string.
- Returns
- A formatted string.
- Description
- Render a HTML division. This creates an HTML element with the required options. It is useful to generate a dynamically refreshing division.
- Parameters
body: String Division body content. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<% div({ refresh: "/getData", period: 2000}) %>
ejs.web endform(): Void
- Description
- End an input form. This closes an input form initiated by calling the form method.
- Description
- Emit a flash message area.
- Parameters
kinds: Object Kinds of flash messages to display. May be a single string ("error", "inform", "message", "warning"), an array of strings or null. If set to null (or omitted), then all flash messages will be displayed. [default: null] options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
retain Number. Number of seconds to retain the message. If <= 0, the message is retained until another message is displayed. Default is 0. TODO - this default implies it is displayed for zero seconds.
- Example
<% flash("status") %> <% flash() %> <% flash(["error", "warning"]) %>
- Description
- Render a form. The generated form HTML will include by default a security token definition to guard against CSRF threats.
This token will automatically be included when the form is submitted and will be validated by the
receiving Controller. To disable this functionality, set options.nosecurity to true. This security token
will be generated once for the view and the same token will be used by all forms on the view page. To use
security tokens outside a form, you need to manually call securityToken in the <head> section of the page.
TODO -- much more doc here - Talk about controllers updating the record.
- Parameters
record: Object Record to display and optionally update. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
hideErrors Don't display model errors. Models retain error diagnostics from a failed write. Setting this option will prevent their display. modal String Make a form a modal dialog. nosecurity Don't generate a security token for the form. securityToken String Override CSRF security token to include when the form is submitted. A default security token will always be generated unless options.nosecurity is defined to be true.
- Description
- Render an image.
- Parameters
src: String Source name for the image. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<% image("pic.gif") %> <% image("pic.gif", { refresh: "\@store/getData", period: 2000, style: "myStyle" }) %> <% image("pic.gif", { click: "\@foreground/click" }) %> <% image("checkout.gif", { click: "\@checkout" }) %> <% image("pic.gif", { remote: "\@store/update" }) %>
- Description
- Render an input field as part of a form. This is a smart input control that will call the appropriate input control based on the model field data type.
- Parameters
name: String Name for the input field. This defines the HTML element name and provides the source of the initial value to display. The field should be a property of the form control record. It can be a simple property of the record or it can have multiple parts, such as: field.field.field. If this call is used without a form control record, the actual data value should be supplied via the options.value property. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<% input("phone") %>
- Description
- Render a text label field. This renders an output-only text field. Use text() for input fields.
- Parameters
text: String Label text to display. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<% label("Hello World") %> <% label("Hello", { refresh: "/getData", period: 2000, style: "myStyle" }) %> <% label("Hello", { click: "/foreground/link" }) %> <% label("Checkout", { click: "\@checkout" }) %>
- Description
- Emit a selection list.
- Parameters
name: String Field name to provide the default value for the list. The field should be a property of the form control record. The field can be a simple property of the record or it can have multiple parts, i.e. field.field.field. The field name is used to create the HTML input control name. If this call is used without a form control record, the actual data value should be supplied via the options.value property. choices: Object Choices to select from. This can be an array list where each element is displayed and the value returned is an element index (origin zero). It can also be an array of key/value array tuples where the first entry is the value to display and the second is the value to send to the app. Or it can be an array of objects such as those returned from a table lookup. Lastly, it can be an object where the property key is the value to display and the property value is the value to send to the app. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
list("stockId", Stock.stockList) list("priority", ["low", "med", "high"]) list("priority", [["low", 0], ["med", 0.5], ["high", 1]]) list("priority", [{low: 3}, {med: 5}, {high: 9}]) list("priority", {low: 0, med: 1, high: 2}) list("priority", [{id: 77, field: "value", ...}, ...])
- Description
- Temporary helper function to format a number. TODO.
- Parameters
fmt: String Format string.
- Returns
- A formatted string 0.
- Description
- Temporary helper function to format the date. TODO - should move to helpers somewhere.
- Parameters
fmt: String Format string.
- Returns
- A formatted string.
- Description
- Create a URI link. The target parameter may contain partial or complete URI information. The missing parts are supplied using the current request and route tables. The resulting URI is a normalized, server-local URI (begins with "/"). The URI will include any defined scriptName, but will not include scheme, host or port components.
- Parameters
target: Object The URI target. The target parameter can be a URI string or object hash of components. If the target is a string, it is may contain an absolute or relative URI. If the target has an absolute URI path, that path is used unmodified. If the target is a relative URI, it is appended to the current request URI path. The target can also be an object hash of URI components: scheme, host, port, path, reference and query. If these component properties are supplied, these will be combined to create a URI. The URI will be created according to the route URI template. The template may be explicitly specified via a "route" target property. Otherwise, if an "action" property is specified, the route of the same name will be used. If these don't result in a usable route, the "default" route will be used. See the Router for more details. If the target is a string that begins with " @" it will be interpreted as a controller/action pair of the form " @Controller/action". If the "controller/" portion is absent, the current controller is used. If the action component is missing, the "index" action is used. A bare " @" refers to the "index" action of the current controller. Lastly, the target object hash may contain an override "uri" property. If specified, the value of the "uri" property will be returned and all other properties will be ignored.
- Options
scheme String URI scheme portion. host String URI host portion. port Number URI port number. path String URI path portion. reference String URI path reference. Does not include "#". query String URI query parameters. Does not include "?". controller String Controller name if using a Controller-based route. This can also be specified via the action option. action String Action to invoke. This can be a URI string or a Controller action of the form. route String Route name to use for the URI template.
- Returns
- A normalized, server-local Uri object. The returned URI will be an absolute URI.
- Example
Given a current request of http://example.com/samples/demo" and "r" == the current request: r.link("images/splash.png") # "/samples/images/splash.png" r.link("images/splash.png").complete(r.uri) # "http://example.com/samples/images/splash.png" r.link("images/splash.png").relative(r.uri) # "images/splash.png" r.link("http://example.com/index.html") r.link("/path/to/index.html") r.link("\@Controller/checkout") r.link("\@Controller/") r.link("\@checkout") r.link("\@") r.link({action: "checkout") r.link({action: "logout", controller: "Admin") r.link({action: "Admin/logout") r.link({action: "\@Admin/logout") r.link({uri: "http://example.com/checkout"}) r.link({route: "default", action: "\@checkout") r.link({product: "candy", quantity: "10", template: "/cart/{product}/{quantity}}")
- Description
- Render a radio button. This creates a radio button suitable for use within an input form.
- Parameters
name: String Name for the input radio button. This defines the HTML element name and provides the source of the initial value to display. The field should be a property of the form control record. It can be a simple property of the record or it can have multiple parts, such as: field.field.field. If this call is used without a form control record, the actual data value should be supplied via the options.value property. choices: Object Choices to select from. This can be an array list where each element is displayed and the value returned is an element index (origin zero). It can also be an array of key/value array tuples where the first entry is the value to display and the second is the value to send to the app and store in the database. Or it can be an array of objects such as those returned from a table lookup. Lastly, it can be an object where the property key is the value to display and the property value is the value to send to the app and store in the database. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
radio("priority", ["low", "med", "high"]) radio("priority", [["low", 0], ["med", 0.5], ["high", 1]]) radio("priority", [{low: 3}, {med: 5}, {high: 9}]) radio("priority", {low: 0, med: 1, high: 2}) radio("priority", Message.priorities)
- Description
- Redirect the client to a new URL. This call redirects the client's browser to a new target specified by the url. Optionally, a redirection code may be provided. Normally this code is set to be the HTTP code 302 which means a temporary redirect. A 301, permanent redirect code may be explicitly set.
- Description
- Process and emit a view to the client. This invokes the given render function with "this" set to the view.
- Parameters
renderer: Function Rendering function. This may be any external function. The function will have its scope modified so that it executes as if it were a member method of the View class.
- Description
- Emit a script link.
- Parameters
target: Object Script URI to load. URI or array of scripts. Call with no arguments or set to null to get a default set of scripts. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
minified If the target is null, a minified option will determine if compressed (minifed) or uncompressed versions of the scripts will be used.
- Description
- Generate a security token for the page and emit a <meta HTML element for the security token. Security tokens are used to help guard against CSRF threats. This token will automatically be included whenever forms are submitted and the token be validated by the receiving Controller. Forms will normally automatically generate the security token and that explicitly calling this routine is not required unless a security token is required for non-form requests such as AJAX requests. The securityToken control should be called inside the <head section of the view page.
- Parameters
options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<head> <% securityToken() %> </head>
- Description
- Convenience routine to set a Http response header in responseHeaders. If a header has already been defined and overwrite is true, the header will be overwritten. NOTE: case is ignored in the header keyword. Access responseHeaders to inspect the proposed response header set.
- Parameters
key: String The header keyword for the request, e.g. "accept". value: String The value to associate with the header, e.g. "yes". overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator.
- Description
- Convenience routine to set multiple Http response headers in responseHeaders. Access responseHeaders to inspect the proposed response header set.
- Description
- Convenience routine to set the (proposed) Http response status code. This is equivalent to assigning to the status property.
- Description
- Render a table. The table control can display static or dynamic tabular data. The client table control manages sorting by column, dynamic data refreshes and clicking on rows or cells.
- Parameters
data Data to display. The data must be a grid of data, ie. an Array of objects where each object represents the data for a row. The column names are the object property names and the cell text is the object property values. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
cell Boolean Set to true to make click or edit links apply per cell instead of per row. The default is false. columns (Array|Object) The columns list can be either an array of column names or an object hash of column objects where each column entry is hash of column options. Column options: align, formatter, header, sort, sortOrder, style, width. params Object Hash of post parameters to include in the request. This is a hash of key/value items. pivot Boolean Pivot the table by swaping rows for columns and vice-versa. showHeader Boolean Control if column headings are displayed. showId Boolean If a columns option is not provided, the id column is normally hidden. To display, set showId to be true. sort String Enable row sorting and define the column to sort by. Defaults to the first column. sortOrder String Default sort order. Set to "ascending" or "descending".Defaults to ascending. style String CSS class to use for the table. The ultimate style to use for a table cell is the combination of style, styleCells, styleColumns and style Rows. styleCells 2D Array of styles to use for the table body cells. Can also provide an array to the column.style property. styleColumns Array of styles to use for the table body columns. Can also use the style option in the columns option. styleRows Array of styles to use for the table body rows. title String Table title. Column options: - align - Will right-align numbers by default
- click - URI to invoke if the cell is clicked
- edit - TODO
- formatter - Function to invoke to format the value to display
- header - Header text for the column
- style - Cell styles
- width - Column width. Can be a string percentage or numeric pixel width
- Example
<% table(gridData, { refresh: "\@update", period: 1000, pivot: true" }) %> <% table(gridData, { click: "\@edit" }) %> <% table(Table.findAll()) %> <% table(gridData, { click: "\@edit", sort: "Product", columns: { product: { header: "Product", width: "20%" } date: { format: date('%m-%d-%y) } } }) %>
- Description
- Render a tab control. The tab control can manage a set of panes and will selectively show and hide or invoke the selected panes. If the click option is defined (default), the selected pane will be invoked via a foreground click. If the remote option is defined, the selected pane will be invoked via a background click. If the toggle option is defined the selected pane will be made visible and other panes will be hidden. If using show/hide tabs, define the initial visible pane to be of the class "-ejs-pane-visible" and define other panes to be "-ejs-pane-hidden". The control's client side code will toggle these classes to make panes visible or hidden.
- Parameters
data: Object Tab data for the control. Tab data can be be a single object where the tab text is the property key and the target to invoke is the property value. It can also be an an array of objects, one per tab. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
click Set to true to invoke the selected pane via a foreground click. remote Set to true to invoke the selected pane via a background click. toggle Set to true to show the selected pane and hide other panes.
- Example
tabs({Status: "pane-1", "Edit: "pane-2"}) tabs([{Status: "/url-1"}, {"Edit: "/url-2"}], { click: "\@someAction"})
- Description
- Render a text input field as part of a form.
- Parameters
name: String Name for the input text field. This defines the HTML element name and provides the source of the initial value to display. The field should be a property of the form control record. It can be a simple property of the record or it can have multiple parts, such as: field.field.field. If this call is used without a form control record, the actual data value should be supplied via the options.value property. If the cols or rows option is defined, then a textarea HTML element will be used for multiline input. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Options
cols Number number of text columns. rows Number number of text rows. password Boolean The data to display is a password and should be obfuscated.
- Example
<% text("name") %> <% text("product.name") %> <% text("address", { escape: true }) %> <% text("password", {value: params.password, password: true}) %> <% text("password", {size: 20}) %>
- Description
- Render a tree control. The tree control can display static or dynamic tree data.
- Description
- Render a partial view. This creates an HTML element with the required options. It is useful to generate a dynamically refreshing division.
- Parameters
viewPath (String|Object) If a string, it is a view template name or the name of an action. If an object, it should have properties: controller and action. Action can be the name of a view template. options: Object Optional extra options. See View for a list of the standard options. [default: expression]
- Example
<% view(viewName) %> @
- Description
- Write data to the stream.Write data to the client. If the stream can accept all the write data, the call returns immediately with the number of bytes written. If writing more data than the stream can absorb in sync mode, the call will block until the data is written. If writing more data than the stream can absorb in async mode, the call will not block and will buffer the data and return immediately. Some streams will require a flush() call to actually send the data. A "writable" event will be issued when the stream can again absorb more data.This will buffer the written data until either flush() or finalize() is called. 0
- Parameters
data: Array Data to write.
- Events
readable Issued when data is written and a consumer can read without blocking. writable Issued when the stream becomes empty and it is ready to be written to.
- Returns
- A count of the bytes actually written.
- Throws
- IOError: if there is an I/O error.
- Description
- Write safely. Write HTML escaped data back to the client.
- Parameters
data: Array Objects to HTML encode and write back to the client. 0.