Flapjax Framework API Documentation
Event Streams
Behaviors
DOM Manipulation
Web Services
DOM Utilities
Miscellaneous Functions
oneE [top]
oneE(val) -> EventStream val

Create an event stream that fires just one event with the value val.

Note that oneE does not immediately fire val. The event is queued and fired after the current event has finished propagating.

Example

The following code prints "first", "second" and "third" in order:

console.log('first');
mapE(function(val) { console.log(val); },oneE('third'));
console.log('second');

zeroE [top]
zeroE() -> EventStream a

Create an event stream that never fires any events.

mapE [top]
mapE(f, argE) -> EventStream b

argE :: EventStream a
f :: a -> b

Transforms a stream of events.

Example

timerE(1000) is an event stream that fires an event every second. The event value is the current time, in milliseconds. The following expression transforms the event stream to return the current time plus one second:

mapE(timerE(1000),function(t) { return t + 1; })

Alternatively, we can use the mapE method of the event object to achieve the same effect.

timerE(1000).mapE(function(t) { return t + 1; })
argE.mapE(f) is a synonym for mapE.
mergeE [top]
mergeE(event_1, ..., event_n) -> EventStream a

event_1 :: EventStream a
...
event_n :: EventStream a

Accepts multiple event streams and merge their events into a single event stream. whenever an event occurs on one of the original streams, it is propagated into the merged event stream.

Example

Suppose we are building a web-based document editor. We wish the save the document every 60 seconds, and when the user clicks the save button:

var saveTimer = timerE(60000);
var saveClicked = extractEventE('save-button','click');
var save = mergeE(saveTimer,saveClicked);
save.mapE(doSave); // doSave does the real work
switchE [top]
switchE(anyEE) -> EventStream a

anyEE :: EventStream (EventStream a)

Given an event stream of event streams, fire events from the most recent event stream.

Example
var domStreamE = receiverE(); // every event is a DOM object
domStreamE.
	switchE().
	extractEventE('mouseover').
	mapE(function(_) { alert('hit!'); });
anyEE.switchE is a synonym for switchE.
condE [top]
condE([boolE,resultE], ...) -> EventStream a

boolE :: EventStream Bool
resultE :: EventStream a

Conditional with multiple branches. The input is a set of pairs. Using argument order to determine priority within one time step (only one event should be sent per timestep), the first tuple with both a pair with a first event occuring of true and second event of type a will have the value of the second event will propagate. No value needs to propagate every time step.

filterE [top]
filterE(sourceE,pred) -> EventStream a

sourceE :: EventStream a
pred :: a -> Bool

Given an event stream and a predicate, filters out the events that do not satisfy the predicate.

Example

The following event stream only contains positive numbers:

numbers.filterE(function (v) { return v > 0; })
sourceE.filterE is a synonym for filterE.
ifE [top]
ifE(testE,trueE,falseE) -> EventStream a

testE :: EventStream Bool
trueE :: EventStream a
falseE :: EventStream a

When an event occurs in the test position, if it is true, and in the same timestep an event occurs in the true branch, propagate the event in the true branch. If the test position receives a false event, then if in the same timestep an event occurs and the false branch, propagate that event. If either no event occurs in the test position or no event occurs in the enabled branch, do not send an event.

testE.ifE is a synonym for ifE.
constantE [top]
constantE(sourceE,val) -> EventStream val

sourceE :: EventStream a

Transforms an event stream by discarding its events' values to return a constant value.

Example

The following code displays an alert box whenever the button is clicked:

var clicks = clicksE('form-button');
clicks.constantE(42).mapE(function(v) { 
  alert('The magic number is ' + v '.'); });
sourceE.constantE is a synonym for constantE.
collectE [top]
collectE(sourceE,init,f) -> EventStream b

sourceE :: EventStream a
init :: b
f :: a b -> b

Given an event stream, an initial value and a combining function, returns an event stream of accumulated results.

Example

The following code uses Javascript's Array.concat method to accumulate an array of events:

original.collectE([],function(new,arr) { return [new].concat(arr); });

Note that the initial value is the empty array. In the resultant event stream of event value, the latest event is first.

The following code ignores the event value, and increments the initial value, effectively counting the number of events that occur. Naturally, the initial value is 0:

original.collectE(0,function(_,count) { return count + 1; });
sourceE.collectE is a synonym for collectE.
andE [top]
andE(sourceE, ...) -> EventStream True

sourceE :: EventStream Bool

Fires an event when all its arguments fire True.

orE [top]
orE(sourceE, ...) -> EventStream True

sourceE :: EventStream Bool

Fires an event when any of its arguments fire True.

notE [top]
notE(sourceE) -> EventStream Bool

sourceE :: EventStream Bool

Negates each event in the event stream.

sourceE.notE is a synonym for notE.
filterRepeatsE [top]
filterRepeatsE(sourceE) -> EventStream a

sourceE :: EventStream a

Filters an event stream, removing successive events that are equal.

Example

This timer signals an event every 0.1 seconds. However, it reports time in seconds.

var secE = timerE(100).mapE(function (ms)
              { return Math.floor (ms / 1000) % 10; });

filterRepeatsE removes the duplicate events from the event stream:

secE.filterRepeatsE()
sourceE.filterRepeatsE is a synonym for filterRepeatsE.
receiverE and sendEvent [top]
receiverE() -> Event a

sendEvent(a,EventStream a);

receiverE creates an event stream that does not receive events from any other event source. However, sendEvent may be used to send an event to a receiverE event source.

Example

sendEvent is useful for integrating Flapjax with existing event-based Javascript code. For example, here is a simplified timer:

function simple_timerE(interval_ms) {
  var evt = receiverE();
  // create and install a callback
  var f = function() { evt.sendEvent((new Date()).getTime()); };
  window.setInterval(f,interval_ms);
  return evt;
}
snapshotE [top]
snapshotE(sourceE,valueB) -> EventStream b

sourceE :: EventStream a
valueB :: Behavior b

Returns an event stream carrying values from valueB. Values are captured when sourceE fires an event.

sourceE.snapshotE is a synonym for snapshotE.
onceE [top]
onceE(sourceE) -> EventStream a

sourceE : EventStream a

Given a stream of events, create a new stream that will send only the first event sent by the original event stream.

sourceE.onceE is a synonym for onceE.
skipFirstE [top]
skipFirstE(sourceE) -> EventStream a

sourceE : EventStream a

Skips the first event in sourceE.

Example

The expression skipFirstE(skipFirstE(sourceE)) skips the first two events from sourceE.

sourceE.skipFirstE is a synonym for skipFirstE.
delayE [top]
delayE(sourceE,intervalB) -> EventStream a

sourceE :: EventStream a
intervalB :: Behavior milliseconds

Delays propagation of the events from sourceE by intervalB milliseconds.

sourceE.delayE is a synonym for delayE.
blindE [top]
blindE(sourceE,intervalB) -> EventStream a

sourceE : EventStream a
intervalB : Behavior Int

Ignores events that fire less than intervalB milliseconds apart. All other events are propagated. Note that intervalB may be time-varying.

sourceE.blindE is a synonym for blindE.
calmE [top]
calmE(sourceE,intervalB) -> EventStream a

sourceE : EventStream a
intervalB : Behavior Int

"Calm" the event stream to fire at most once every intervalB milliseconds. Events that occur sooner are delayed to ocur intervalB milliseconds after the most recently-fired event. Only the most recent event is delayed. So, if multiple events fire within intervalB, only the last event will be propagated.

sourceE.calmE is a synonym for calmE.
startsWith [top]
startsWith(sourceE,initialVal) -> Behavior a

sourceE :: Behavior a
initialVal :: a

Given an event stream and an initial value, create a time varying value that starts as the initial value and changes value whenever an event occurs, taking on the value of that event.

sourceE.startsWith is a synonym for startsWith.
changes [top]
changes(behavior) -> EventStream a

behavior :: Behavior a

Given a time varying value, make an event steam whose events are the values of the behaviour whenever it changes.

behavior.changes is a synonym for changes.
constantB [top]
constantB(val) -> Behavior val

Create a behavior with a constant value.

delayB [top]
delayB(sourceB,delay) -> Behavior a
delayB(sourceB,delayB) -> Behavior a

sourceB :: Behavior a
delayB :: Behavior milliseconds
delay :: milliseconds

Given a time varying value, create a new time varying value whose value at any point in time is the value of the original value from agiven amount of time before. The delay time is specified in milliseconds. As this would leave the value undefined until the delay time has passed at least once, such as at program initialization, there is also an optional initialization. Both the initialization argument and amount of time to delay may be time varying values.

sourceB.delayB is a synonym for delayB.
valueNow [top]
valueNow(sourceB) -> a

sourceB :: Behavior a

Returns the current value of sourceB. This is a primitive method that should not be used under normal circumstances. liftB or snapshotE may be more appropriate.

switchB [top]
switchB(sourceBB) -> Behavior a

sourceBB :: Behavior (Behavior a)

When the value of a time varying value is time varying itself, which is common when dealing DOM objects.

sourceBB.switchB is a synonym for switchB.
andB [top]
andB(valueB, ...) -> Behavior Bool

Returns True when all arguments are True and False otherwise.

orB [top]
orB(valueB, ...) -> Behavior Bool

Returns True when any argument is True and False otherwise.

notB [top]
notB(valueB) -> Behavior Bool

valueB = Behavior a

This function is short for:

valueB.liftB(function(v) { return !v; })
liftB [top]
liftB(f,arg_1, ..., arg_n) -> Behavior result


f = (arg_1 ... arg_n -> result) or Behavior (arg_1 ... arg_n -> result)
arg_1 = a_1 or Behavior a_1
...
arg_n = a_n or Behavior a_n

Create a time varying value that is a function of other time varying values. The function itself may be a time-varying value.

condB [top]
condB([conditionB,resultB], ...) -> Behavior a

conditionB = Behavior Bool
resultB = Behavior a

Evaluates to the first resultB whose associated conditionB is True.

ifB [top]
ifB(conditionB,trueB,falseB) -> Behavior a

conditionB = Behavior Bool
trueB = Behavior a
falseB = Behavior a

Switches between trueB and falseB, as the value of conditionB varies between true and false.

Example
var t = timerB(1000);
var t1 = t.liftB(function(v) { return v + 1; });
var less_than = function(xB,yB) { return liftB(function(x,y) { return x < y; },xB,yB) };

trueB = ifB(less_than(t,t1),true,false);

Since t < t1 is always true, trueB is always true.

chooseB is a synonym for ifB.
timerB [top]
timerB(interval) -> Behavior Int
timerB(intervalB) -> Behavior Int

interval :: milliseconds
intervalB :: Behavior milliseconds

Create a time varying value with the current time in milliseconds, updated by an interval argument (that may be time varying).

blindB [top]
blindB(sourceB,intervalB) -> Behavior a

sourceB : Behavior a
intervalB : Behavior Int

Similar to blindE but for behaviors.

sourceB.blindB is a synonym for blindB.
calmB [top]
calmB(sourceB,intervalB) -> Behavior a

sourceB : Behavior a
intervalB : Behavior Int

Similar to calmE, but for behaviors.

sourceB.calmB is a synonym for calmB.
Time-varying DOM Elements [top]
TAG :: Behavior { attribute-name: attribute-value, ...} * Behavior HTMLElement * ... -> Behavior HTMLElement
TAG :: Behavior HTMLElement * ... -> Behavior HTMLElement // no attributes

Flapjax includes support for DOM elements with time-varying components. For each HTML Element, Flapjax defines a function with the same name that constructions the corresponding element.

Example
var secondsB = timerE(1000).collectE(0,function(_,x) { return x + 1; }).startsWith(0);
var spanB = SPAN("We've been running for ",secondsB," seconds");

Note that this example intersperses a behavior (spanB) with constant values.

insertDomB [top]
insertDomB :: Behavior HTMLElement * HTMLElement or id [ * location ] -> void

location = 'before' U 'after' U 'leftMost' U 'rightMost' U 'over' U 'beginning' U 'end'

insertDomB(Behavior HTMLElement,HTMLElement or id [, location]) -> void
mouseTopB [top]
mouseTopB(Element) -> Behavior y-coordinate

A behavior carrying the y-coordinate of the mouse, relative to the specified element.

Example
var yB = mouseTopB(document);

yB is the coordinate of the mouse, relative to the entire document.

mouseLeftB [top]
mouseLeftB(Element) -> Behavior x-coordinate

A behavior carrying the x-coordinate of the mouse, relative to the specified element.

mouseB [top]
mouseB(Element) -> Behavior xy

xy = { left: Int; top: Int }

A behavior carrying the mouse's coordinates, relative to the specified element.

extractValueB [top]
extractValueB(formElement) -> Behavior value

formElement = Element or Element-id

Returns a behavior carrying the value of the specified form element.

$B is a synonym for extractValueB.
extractValueE [top]
extractValueE(formElement) -> EventStream value

formElement = Element or Element-id

Returns an event stream that carries the value of formElement. A new event fires whenever the value changes.

extractEventE [top]
extractEventE(element,eventName) -> EventStream DOMEvent
extractEventE(elementB,eventName) -> EventStream DOMEvent

element = Element or Element-id
elementB = Behavior element
eventName = String

Returns an event stream that carries DOM events from element, of the type eventName. Each DOMEvent is a browser-dependent data-structure, derived from the DOM Event Specification.

$E is a synonym for extractEventE.
clicksE [top]
clicksE(element) -> EventStream ClickEvent

clicksE(element) is shorthand for extractEventE(element,'click').

timerE [top]
timerE(milliseconds) -> EventStream Int
timerE(millisecondsB) -> EventStream Int

milliseconds : Int
millisecondsB : Behavior milliseconds

Given an interval in milliseconds, returns an event stream that repeatedly fires an event as the interval lapses. The interval itself may be a behavior. The value of each event is the system time, in milliseconds.

Example

The following event stream fires an event each second. The event value is the current data and time, formatted as a string:

function formatDate(t) {
  return (new Date(t)).toLocaleString();
}

timerE(1000).mapE(formatDate)

Note that the interval may be a behavior. The following expression's interval changes as the user enters a different interval:

timerE(extractValueB('interval-text-box')).mapE(formatDate)

timerE is a method of behavior objects. The preceding expression may be written as:

extractValueB('interval-text-box').timerE().mapE(formatDate)
disableTimer [top]
disableTimer(timer);

Given an event timer, make it stop updating.

extractValueOnEventE [top]
extractValueOnEventE(anyE,formElement) -> EventStream value

anyE = EventStream
formElement = Element or Element-id

Extracts the value of formElement whenever an event occurs on anyE.

extractIdB [top]
extractIdB(id [, changes]) -> Behavior Element

id = String
changes = Behavior DOM

The element associated with a specified id may change over time. Whenever the value changes changes, the element with the id id is reextracted. If changes is not specified, the element id is reextracted whenever an inserted DOM element changes.

insertDomE [top]
insertDomE(source, dest, placement = 'over');

source = EventStream Element
dest = Element-Id or Element
placement = 'before' or 'after' or 'leftMost' or 'rightMost' or 'over' or 'beginning' or 'end'

Similar to insertDomB, but inserts Elements from an event-stream instead of a behavior.

insertValueE [top]
insertValueE(valueE, dest, field, ...);

valueE = EventStream
dest = Element or Element-id
field = String

Inserts each event in valueE info the field field of the elmeent dest

Example
var textField = TEXT();
var button = BUTTON();

function getDate() { return (new Date()).toString(); };

insertValueE(extractEventE(button, 'click').mapE(getDate), textField, 'value');

This code inserts the current date and time into textField whenever button is clicked.

insertValueB [top]
insertValueB(valueB, dest, field, ...);

valueB = Behavior
dest = Element or Element-id
field = String

Inserts the time-varying value valueB info the field field of the elmeent dest. This function is similar to insertValueE.

tagRec [top]
tagRec(Array eventName, (Array eventName -> ElementB)) -> Behavior Element

An element may be a function of some event and behaviours, while those same events and behaviours might als be functions of the tag. tagRec is a convenience method for writing such cyclic dependencies. Also, as certain updates may cause a tag to be destroyed and recreated, this guarentees the extracted events are for the most recently constructed DOM node.

Example
tagRec(
  ['mouseover', 'mouseout'],
  function (overE, outE) {
    return DIV(
      { style: {
        color:
          mergeE(overE.constantE('#FFF'), outE.constantE('#000')).
          startsWith('#000')}},
      'mouse over me to change color!');
  });

Create a tags whose background color is white on mouse over and black on mouseout, starting as black.

getWebServiceObjectE [top]
getWebServiceObjectE(requestE) -> EventStream response

requestE = EventStream request
request = {
  url: string,
  request: 'get' | 'rest' | 'post' | 'rawPost',
  response: 'json', 'xml', 'plain',
  fields: object | undefined,
  body: string | undefined
  async: bool
}

Sends a stream of requests to a web server and receives a stream of responses.

url is the address of the web service. getWebServiceObjectE is based on XMLHttpRequest, so the service must be on the same server as your application.

request specifies how the request should be encoded.

response specifies how the response is decoded. plain indicates that the body should not be decoded. This is the default behavior. json indicates that the response should be parsed as a JSON string. xml indicates that the response is XML.

getForeignWebServiceObjectE [top]
getForeignWebServiceObjectE(requestE) -> responseE

Note: You must call initFlapjaxForeignWSO before using this function.

This function has the same interface as getWebServiceObjectE. Requests are made through a Flash object, so the url is subject to the Flash Player's cross-domain policy.

evalForeignScriptValE [top]
evalForeignScriptValE(urlArgE) -> EventStream result

urlArgE = EventStream { url: string, globalArg: string }

Evaluates the JavaScript code at url; url may be on a remote server. The code is expected to set the global variable named globalArg. Flapjax will poll this variable and send its value to the result stream when it is set.

Example

See the Delicious demos.

initFlapjaxForeignWSO [top]
initFlapjaxForeignWSO(baseUrl);

baseUrl : url

This function must be called before getForeignWebServiceObjectE is called. baseUrl must be base URL of the Flapjax library.

Example
initFlapjaxForeignWSO('http://www.flapjax-lang.org/fx');
getElementsByClass [top]
getElementsByClass(className) -> Array Element
getElementsByClass(className,rootElement) -> Array Element
getElementsByClass(className,rootElement,elementTag) -> Array Element

className = String
rootElement = Element or undefined
elementTag = String

Returns an array of elements with the specified className. If rootElement is specified, the returned elements are children of rootElement. If elementTag is specified, it constraints the elements to have the specified tag.

Example
getElementsByClass('article',document,'div')

Returns all div elements of the class article.

$$ is a synonym for getElementsByClass.
getObjsA [top]
getObjsA(elementId, ...) -> Array Element

elementId = String

Returns an array of elements, selected by their ids.

$A is a synonym for getObjsA.
getObjs [top]
getObjs(elementId, ...) -> { elementId: Element, ... }

elementId = String

Returns a dictionary of elements, keyed by their ids.

$O is a synonym for getObjs.
getObj [top]
getObj(elementId) -> Element
getObj(Element) -> Element

elementId = String

Returns the element with the id elementId.

$ is a synonym for getObj.
readCookie [top]
readCookie(fieldName) -> String or undefined

fieldName = String

Returns the value associated with fieldName from the cookie.

swapDom [top]
swapDom(existingElement,newElement) -> Element

existingElement = Element or ElementId
newElement = Element or ElementId

Removes existingElement from the document, replacing it with newElement. The removed element is returned.

getURLParam [top]
getURLParam(paramName) -> String or undefined

paramName = String

Returns the value of an GET argument supplied to the URL. The initial URL is stored when the Flapjax framework is initialized, so subsequent modifications do not affect this function.

$URL is a synonym for getURLParam.
cumulativeOffset [top]
cumulativeOffset(element) -> { left: integer, top: integer }

Returns the absolute position of an element relative to the top-left corner of the window.

slice [top]
slice(array, startIndex) -> Array
slice(array, startIndex, endIndex) -> Array

Returns a subsequence of array, starting from the element at startIndex and upto and excluding the element at endIndex. If endIndex is not specified, it is assumed to be array.length - 1.

member [top]
member(elt,array) -> Bool

elt : a
array : Array a

Determines whether elt is an element of array. Comparision is performed with the === operator.

map [top]
map(f,array_1, ..., array_n) -> Array r

array_1 : Array a_1
...
array_n : Array a_n
f : (a_1 ... a_n -> r)

Applies f pointwise across the supplied arrays and returns an array of results.

filter [top]
filter(predicate,array) -> Array a

predicate : a -> bool
array : Array a

Filters out the elements that fail to satisfy predicate.

forEach [top]
forEach(f,array_1, ..., array_n);

array_1 : Array a_1
...
array_n : Array a_n
f : (a_1 ... a_n -> r)

Similar to map, but does not accumulate an array of results

.
fold [top]
fold(f,init,array_1, ..., array_n) -> b

init : b
f : a_1 ... a_n b -> b
array_1 : Array a_1
...
array_n : Array a_n

Reduces the arrays left-to-right.

foldR [top]
foldR(f,init,array_1, ..., array_n) -> b

init : b
f : a_1 ... a_n b -> b
array_1 : Array a_1
...
array_n : Array a_n

Reduces the arrays right-to-left.