Obviel API

Obviel core

iface(name[, *bases])

Declare an iface.

Arguments:
  • name (string) – A unique string identifying the iface.
  • *bases – Optional extra iface strings that are interpreted as base ifaces that this iface extends.

Register an iface with the name name. Note that declaring an iface is not required in order to use it; you can just refer to any iface, declared or not, by name.

A registered iface always automatically extends a special iface base.

provides(obj, base)

Check whether an object provides an iface.

Arguments:
  • obj – Any JavaScript object.
  • base (string) – A string identifying an iface.
Returns:

true if obj provides iface base (or an iface that extends base.

extendsIface(name, base)

Register a new base iface for an iface.

Arguments:
  • name (string) – Identifies the iface to extend.
  • base (string) – Identifies the base iface that this iface extends.
ifaces(obj)

Obtain all ifaces that this object provides, going recursively through base interfaces, breadth first.

If no ifaces attribute is available, the JS type of the object is returned instead.

Arguments:
  • obj – Any JavaScript object
Returns:

a list of ifaces that the obj provides.

class View(settings)
Arguments:
  • settings – an object of which the properties will become properties of the view itself.

You can create a View by instantiating one and then registering it with view(), but that function also allows creation of a new view directly from a settings object.

If you want to create your own view types that provide more features particular to specific use cases, you should derive your view from the View class. One example of this is Widget() from the Obviel forms library.

view(view)

Register a view with Obviel. This allows Obviel to look up the view for the iface with which the view was registered.

Arguments:
  • view – a view object to register with Obviel. As a convenience, you can also provide a bare JavaScript object, which will be converted to a View() object with the object’s properties.
transformer(transformer)
Arguments:
  • transformer – a function with the function(obj, url, name) signature, or function(obj, url), or function(obj).

Register a transformer function with Obviel. Obviel will pass any object retrieved from the server using URL access (i.e. a hyperlink reference in an object) through this transformer function.

The transformer function has three arguments:

obj

The object retrieved from the server that can be transformed.

url

The URL used to access the object on the server. Could be used to determine what transformation to apply. Optional.

name

The name used to render the view. Optional.

The transformer function must return the transformed object.

By default Obviel does no transformation, and objects are passed from the server to Obviel unchanged.

You can disable the transformer function by passing in null.

element.render(obj[, name, callback, errback])

Render a view for an object on a jQuery element. This instantiates a view by cloning it from the registered view and then calls its View.render() method.

Arguments:
  • obj – The JavaScript object to render. Alternatively this can be a string, which will then be interpreted as a URL. The URL will be fetched and the resulting JSON object will be the object to render.
  • name – The name of the view to render for the object. If not supplied the name default will be used.
  • callback – A callback function to call when the rendering has been completed. this will be the view instance that was used for the rendering.
  • errback – currently not supported.

All methods of the View() object will have access to the following properties on this during rendering:

  • el: the jQuery element that the view is being rendered on.

  • obj: the object being rendered.

  • callback: the callback function, if supplied.

  • errback: the errback function, if supplied.

  • registry: the Registry() in which the view was

    looked up.

element.rerender([callback, errback])
element.view()
element.parent_view()
element.unview()

View options

Views have a number of options you can pass into them in the settings parameter when registering a view using view(). Views also define some convenience methods.

class view()
iface

The iface (a string) for which the view is registered. The view will only be looked up on objects that provide the given iface.

While it is optional and defaults to registering the view for all JavaScript objects, you would almost always want to supply an iface property to a view.

name

The name of the view. It is optional, and defaults to default. The name is used when a view is looked up, along with the iface, but for lookup also the default name is default. The difference between name and iface during lookup that iface is provided from the object being rendered, while the name is provided by the calling code as an argument to element.render().

render

A function which will be added as a method to the view. In it, the developer can refer to this.obj to access the object the view is rendering, and this.el to access the jQuery DOM element on which the view is rendering. The el property is typically manipulated in the render method to make the view actually do something.

Supplying a render method is optional.

before

An optional function that will be called before any rendering (template or otherwise) takes place. This is most useful to to manipulate this.obj to set extra information in it that the template needs.

cleanup

An optional cleanup function that will be called when the (non-ephemeral) view is being cleaned up from the element it was rendered on, either explicitly because element.unview() was called on it, or implicitly because something else is being rendered on the element.

ephemeral

A boolean value. By default it is false. If set to true, the view will not be associated with the element. This is useful for views that are not really associated with the DOM, such as popup messages or views that redirect to other views.

html

A string with a snippet of HTML that should be inserted into the DOM upon rendering. This will be done before any view.render() function is called.

This property is optional, and by default there will be no HTML snippet insertion.

html_url

A string with a URL to a resource with a HTML snippet in it. This HTML snippet will be loaded if the URL has not been previously seen, otherwise it is retrieved from a cache. The HTML snippet is inserted into the DOM as with html.

This property is optional.

jsont

A string with a JSON template. The template is rendered with the object being rendered as the context, and the resulting HTML snippet is inserted into the DOM as with html.

This property is optional.

jsont_url

A URL referencing a resource that is a JSON template. This template will be loaded if the URL has not been previously seen, otherwise it is retrieved from a cache. The HTML snippets that results from rendering the template will be inserted into the DOM as with html.

This property is optional.

subviews

A JavaScript object literal describing subviews of this view. Each property name define a jQuery selector that will be issued on the element being rendered by the outer view that is being rendered. The resulting elements will be have the sub view rendered on them. The property value identifies a property on the model object that is being rendered. This property is accessed: if it is a sub object, it will be rendered directly. If it is a string, this string is interpreted as a URL identifying the object to be rendered, as with element.render().

To render a named subview, use a property value that is an array instead: the first item is interpreted as the property name identifying the subobject or URL to be rendered, and the second item is the view name to use to look up the subview.

events

A JavaScript object literal describing event handlers to hook up for this view. Each property name is the name of the event, such as click. The property value is another object literal, where each key is a jQuery selector and the value either a function or a string that indicates the event handler. The jQuery selector determines to which elements in the view the event handlers are bound.

If the event handler is a function, this function is the event handler. It will receive a single parameter that is the event. The event object has a view property that you can use to access the view that issued the event.

If the event handler is a string, this is used to identify a method of the view that is the event handler. This method also receives a parameter ev that has a view property, but the view can in this case also be accessed as this.

object_events

A JavaScript object literal describing event handlers to hook up to the object rendered by this view. Each property name is the name of the event. These are generally custom event names you can come up with yourself. The property value is either a function or a string indicating the event handler.

If the event handler is a function, this function is the event handler. It will receive a single parameter that is the event. The event object has a view property that you can use to access the view that issued the event.

If the event handler is a string, this is used to identify a method of the view that is the event handler. This method also receives a parameter ev that has a view property, but the view can in this case also be accessed as this.

rerender()

A convenience method that is useful to refer to using declarative events or object events. This method when called will re-render the object on the element. This is useful for instance when the underlying object has changed.

Obviel Template

Everything is in the obviel.template namespace.

class CompilationError()

Exception. Something went wrong during compilation of a template.

el

The JavaScript DOM node, typically an element node, on which compilation failed.

message

Message describing what went wrong during compilation.

class RenderError()

Exception. Something went wrong during compilation of a template.

el

The JavaScript DOM node, typically an element node, on which rendering failed.

message

Message describing what went wrong during rendering.

register_formatter(name, func)

Register a formatter. Is done when the UI starts up (per page), before any templates are compiled.

Arguments:
  • name (string) – the name of the formatter. This is how it is addressed in the template language (using {foo|formatter_name}).
  • func (function) – the formatting function. It gets the text (string) to format as its argument and should return the formatted text.
clear_formatters()

Clear all previously registered formatters. Typically used during unit test teardown.

register_func(name, func)

Register a element adjustment function. Is done when the UI starts up (per page), before any templates are compiled.

Arguments:
  • name (string) – the name of the func. This is how it is addressed in the template language (using data-func="func_name").
  • func (function) – the function that manipulates the element. This function takes 1 to 3 arguments: the jQuery element el to manipulate, a variable resolver function (optional) and a translations object (optional). Should manipulate the element, for instance by using el.addClass. The variable resolver function can be used by the function to look up variables; get the value of variables in the current scope by calling it with a variable name as a string (variable(variable_name)).
clear_funcs()

Clear all previously registered funcs. Typically used during unit test teardown.

class Template()

A template. To instantiate and compile, create a new Template object with a text argument. The text argument should be a HTML fragment that will be compiled.

Can throw CompilationError() if the text could not be compiled.

render(el, obj, translations)

Render template on jQuery element el, using obj to resolve variables, and using translations to look up translations.

Arguments:
  • el (object) – jQuery element to render the template on.
  • obj (object) – Object to render. Variables in the templates will be resolved from obj.
  • translations (object) – A translations lookup registry. Used to look up message ids. Must define a method gettext that takes a single message id argument that returns the translated text. Optional argument.
variables(translation, variables)

A simple way to interpolate variables into a text, in particular for the purposes of i18n.

Given a text with variables (marked with { and }) and an object (hash) of variables, interpolate variables into text. This can be used from JavaScript to interpolate Obviel Template-like translation variables, instead of jsgettext’s strargs, which only works with positional values.

Arguments:
  • text (string) – The text (with variables).
  • arguments (object) – A key-value mapping where the key is the variable name.
Returns:

The text with variables interpolated.

tokenize(text)

Tokenize text using Obviel Template rules. Name tokens are marked by { and }, the rest are text tokens.

Arguments:
  • text (string) – Text to tokenize.
Returns:

an array of token objects. Each token object has a type property that indicates the token type (NAME_TOKEN or TEXT_TOKEN, and a value property. In case of NAME_TOKEN this is the name between { and }, in case of TEXT_TOKEN this is the text.

Obviel Forms

A form structure is could be returned from the server-side but an also be defined on the client. It should have the iface viewform.

Form options

class viewform()
widgets

An array of form widget objects.

controls

An array of form control objects. Defaults to an empty array.

data

The object representing the form contents. Defaults to the empty object and is maintained by the form.

disabled

A boolean. If true, the whole form is rendered in a disabled state and cannot be submitted.

validation_url

A URL to do global validation on. Submitted to this URL will be the form’s data object (as JSON). The server needs to decode this JSON object and do validation on it. The server returns a data structure (as JSON) with the same structure as what was submitted, with the values replaced by error messages (or left out). The minimum object a global validator needs to return is the empty ({}) object. This object will be placed in the global_errors attribute of the form.

errors

The object representing the error messages currently visible in the form. If this object is not empty, form submission will not proceed.

This defaults to the empty object and is maintained by the form.

global_errors

The object representing server-generated error messages currently visible in the form. If this object is not empty, form submission will not proceed.

This defaults to the empty object and is maintained by the form.

Widgets

class Widget()
name

The internal name of the widget. This will be the name of the property under which the inputted value will be stored in the data object.

This must therefore be a valid avaScript property name.

title

The label that will be shown for the widget in the user interface.

description

A longer description of the widget that will be shown in the user interface. May be omitted.

validate

A sub-object describing how this widget is to be validated. Validation properties differ per widget.

validate.defaultvalue

The default value that should be shown in the widget if no specific value is available in the data object.

class InputWidget()

iface: input_field

Base class for all widgets based on the <input type="text"> field.

Derives from Widget().

width

Width of the field in em. By default there is no explicit width and the system uses the browser-defined default width of the input field.

max_length

The maximum length that may be entered into this widget by the user. This is a physical limitation in the browser, not a validation limitation. By default there is no max length.

disabled

Render the widget as disabled and allow no input. By default, disabled is false.

validate.required

This widget is required: a value must be entered by the user before the form can be submitted. By default, widgets are not required.

Example:

validate: {
  required: true
}
class TextLineWidget()

iface: textline_field

Lets the user enter a single line of text, in an <input type="text"> widget. Becomes a string in the data object.

Derives from InputWidget().

validate.min_length

The minimum input length in characters allowed.

validate.max_length

The maximum input length in characters allowed.

validate.regs

An array of zero or more objects. Each object must have a reg property which is a JavaScript style regular expression, and a message property which is a string. If the input does not match reg, message will be displayed as the error message.

This allows you to write regular expression based custom validators for user input.

class TextWidget()

iface: text_field

Lets the user enter a multiline text in a <textarea> widget. Becomes a string in the data object.

Derives from TextLineWidget().

width

The width of the textarea in em.

height

The height of the textarea in em.

class IntegerWidget()

iface: integer_field

Lets the user enter an integer number. Floating point numbers are not accepted, only integers. Becomes a JavaScript number in the data object.

Derives from InputWidget().

validate.allow_negative

If true, negative numbers are allowed as input. Defaults to false, not allowing negative numbers.

validate.length

Only allow input to a fixed number of digits given by length. If not set, any amount of digits will be allowed.

class FloatWidget()

iface: float_field

Lets the user enter a floating point number. Becomes a JavaScript number in the data object.

Derives from InputWidget().

validate.separator

Define the floating point separator. By default this is the period (.), but could be set to , or something else to suit other locales.

validate.allow_negative

If true, negative numbers are allowed as input. Defaults to false, not allowing negative numbers.

class DecimalWidget()

iface: decimal_field

Lets the user enter a decimal number. Becomes a string in the data object for parsing into a server decimal object.

Derives from InputWidget().

validate.separator

Define the decimal separator. By default this is the period (.), but could be set to , or something else to suit other locales.

validate.allow_negative

If true, negative numbers are allowed as input. Defaults to false, not allowing negative numbers.

validate.min_before_sep

Minimum amount of digits that need to be present before the separator. If omitted, there is no minimum.

validate.max_before_sep

Maximum amount of digits that are allowed to be present before the separator. If omitted, there is no maximum.

validate.min_after_sep

Minimum amount of digits that need to be present after the separator. If omitted, there is no minimum.

validate.max_after_sep

Maximum amount of digits that are allowed to be present after the separator. If omitted, there is no maximum.

class BooleanWidget()

iface: boolean_field

Lets the user enter a boolean, true or false in a checkbox, using <input type="checkbox">.

Becomes a JavaScript boolean in the data object.

Derives from Widget().

class ChoiceWidget()

iface: choice_field

Lets the user select a choice from a drop-down box. This uses <input type="select">.

Becomes a string in the data object.

Derives from Widget().

empty_option

The value that will be shown and submitted if the field is not filled in. If not given, the first option in the drop down list will be the default if the field is required.

width

The width of the drop-down box in em.

choices

An array of choices that the user can select. Each entry in the array is an object with a value and a label property. The value will be the value submitted, and the label will be how this value is represented in the user interface.

class DisplayWidget()

iface: display_field

This is a display-only field that the user is not allowed to edit. The value will be shown in a <span> element.

The server code is responsible for really forbidding changes to fields represented by display widget.

Derives from Widget().

class HiddenWidget()

iface: hiden_field

This is special form of the display field that will be hidden from view, represented using <input type="hidden">.

Derives from DisplayWidget()

class DatePickerWidget()

iface:: datepicker_field

This is data input widget which offers picking a date from a calendar. Is represented in data in the yy-mm-dd format, where yy is a four digit year, for example 2011-10-01.

Since this widget depends on jquery-ui for its implementation, it is maintained in a separate field, obviel-forms-datepicker.js, which should be included to be able to use this widget.

Derives from TextLineWidget()

dateFormat

The format that the date should be displayed as. Note that the date will always be saved in yy-mm-dd format, where yy is a four-digit year, so for example 2011-11-01.

This follows the rules from jquery-ui’s datepicker:

http://jqueryui.com/demos/datepicker/#option-dateFormat

http://docs.jquery.com/UI/Datepicker/formatDate

By default the date format is mm/dd/yy.

showOn

When to show the date picker.

This follows the rules from jquery-ui’s datepicker:

http://jqueryui.com/demos/datepicker/#option-showOn

By default the datepicker is shown when the button is clicked.

constrainInput

This follows the rules from jquery-ui’s datepicker:

http://jqueryui.com/demos/datepicker/#option-constrainInput

By default it is set to false.

class AutocompleteWidget()

iface:: autocomplete_field

This is a text line input with autocompletion, and can therefore be used like a ChoiceWidget(). Autocomplete widgets can either include all options directly in the form structure, or supply a server URL on which to look up values to autocomplete. The latter is more scalable if the amount of possible choices is very large.

Since this widget depends on jquery-ui for its implementation, it is maintained in a separate field, obviel-forms-autocomplete.js, which should be included to be able to use this widget.

Derives from TextLineWidget()

data

The autocomplete data. This may either be an array of objects with properties label and value, much like the possible values for a ChoiceWidget(), or it can a string, in which case it is interpreted as a URL.

If interpreted as a URL, the URL will get either a single identifier parameter or a combination of a term and limit parameters. If a single identifier parameter, the server should interpret this as a value and should return the label that belongs to it. If a term and a limit parameter, term is a search term that the server should use to look up matching label/value pairs, and return them as an array with objects each with a label and value property. The limit parameter is used to indicate to the server the maximum amount of matches the server should return.

Custom widgets

Custom widgets will need to subclass InputWidget() and provide some methods. This is the typical pattern:

obviel.iface('custom_field', 'input_field')

// constructor
module.CustomWidget = function(settings) {
   settings = settings || {};
   var d = {
       iface: 'custom_field' // set up iface
   };
   $.extend(d, settings);
   module.InputWidget.call(this, d); // call superclass
};

// set up inheritance
module.CustomWidget.prototype = new module.InputWidget();

module.CustomWidget.prototype.validate = function(value) {
  // use inherited validate function first
  var error = module.InputWidget.prototype.validate.call(this, value);
  // if we have an error in inherited validation, we are done, return
  // that error
  if (error !== undefined) {
      return error;
  }
  // custom validation goes here, either do: return undefined (or
  // plain bare return) or return error message
  return undefined;
}

// convert function is necessary if we convert to non-String JavaScript
// value. Can also be used for strings even if we don't convert
// away from it, for instance to check whether a date string is really
// parseable at all, and to format it to a common format if so.
// in addition convert and its pair convert_back can be used to update
// the browser DOM in more complex ways than the default implementation
// allows.
module.CustomWidget.prototype.convert = function(value) {
  // convert the empty input to null, so that validation for
  // required can do its work
  if (value === '') {
      // return an object with a ``value`` property with the converted value.
      return {value: null};
  }
  // try to interpret the input as the value type we want
  var asint = parseInt(value, 10);
  // if the interpretation did not succeed, return an object
  // with an ``error`` property with the error message.
  if (isNan(asint)) {
      return {error: 'not a number'};
  }
  // return an object with a ``value`` property with the converted value.
  return {value: asint};
}

// convert a JavaScript representation back into the widget representation
// (typically a string)
module.CustomWidget.prototype.convert_back = function(value) {
  // super call
  value = module.InputWidget.prototype.convert_back.call(this, value);
  return value.toString();
}

// finally register the widget as a view with Obviel
obviel.view(new module.CustomWidget());

Traject

Everything is in the traject namespace.

class ParseError()

A parse error when parsing a path.

message

The error message.

class ResolutionError()

Error resolving a path to an object: object cannot be found.

message

The error message.

class LocationError()

Error constructing a location (or path) for an object.

message

The error message.

class RegistrationError()

Error during registration.

message

The error message.

class Patterns()
register_converter(converter_name, converter_func)

Register a variable converter.

Arguments:
  • converter_name (string) – The name of the converter as it will appear in the variable declaration ($foo:<converter_name>).
  • converter_func (function) – A function that takes the variable to convert and returns the converted variable.
register(pattern_str, lookup)

Register a lookup function for a path pattern.

Arguments:
  • pattern_str (string) – A path pattern. These are zero or more steps separated by /, where each steps is either a string, or a $variable (or $variable:converter).
  • lookup (function) – A function that should return the object matching the path variables. It will receive a single variables object as an argument, and its properties are the concrete values used in the path in place of the variables. It can also return null or undefined, indicating thatd the object cannot be found.

Can throw ParseError() if the path cannot be parsed.

Can throw RegistrationError`() if the path cannot be registered due to unknown converters or conflicts in registration.

register_inverse(iface, pattern_str, inverse)

Register an inverse function (from object to variables) for objects of an iface and a pattern.

Arguments:
  • iface (string) – The iface that this inverse is registered for. When an object is located, the iface of the object is used to look up the inverse function.
  • pattern_str (string) – A path pattern as for register(). This is used to reconstruct the path for the objects.
  • inverse (function) – A function that takes an object as an argument and returns a variables object for it that can be used to reconstruct its path, so should have a property for each of the variables in the path.
pattern(iface, pattern_str, lookup, inverse)

Register both a path lookup as well as the inverse at the same time.

Arguments:
  • iface (string) – The iface that this inverse is registered for. When an object is located, the iface of the object is used to look up the inverse function.
  • pattern_str (string) – A path pattern as for register(). This is used to reconstruct the path for the objects.
  • lookup (function) – A function that should return the object matching the path variables. It will receive a single variables object as an argument, and its properties are the concrete values used in the path in place of the variables.
  • inverse (function) – A function that takes an object as an argument and returns a variables object for it that can be used to reconstruct its path, so should have a property for each of the variables in the path.

Can throw ParseError() if the path cannot be parsed.

Can throw RegistrationError() if the path cannot be registered due to unknown converters or conflicts in registration.

set_default_lookup(f)

Register a function that looks up a default object for those paths that don’t have a more specific lookup registered for them.

Param :function f: A function that returns a default object.
resolve(root, path)

Resolve a path to an object according to registered patterns, starting at root.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • path (string) – A concrete path. It will be matched with the registered paths to find the lookup function.
Returns:

The object found.

Can throw ResolutionError() in case the path cannot be resolved to an object.

resolve_stack(root, stack)

Resolve a stack to an object according to registered patterns, starting at root. A stack is a stack of steps in a path, in reverse order.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • stack (array) – A stack of steps, in reverse order from the path. It will be matched with the registered paths to find the lookup function.
Returns:

The object found.

Can throw ResolutionError() in case the stack cannot be resolved to an object.

consume(root, path)

Resolve a path as far as it can be resolved according to registered patterns, then stop resolving the path. Does not throw a ResolutionError(), instead simply stops.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • path (string) – A concrete path. It will be matched with the registered paths to find the lookup function.
Returns:

An object with three properties, unconsumed, an array of steps that could not be resolved (in stack form, reverse order), consumed, those steps that have been successfully consumed when resolving the path, and obj, the object found at the end of path consumption (if no path could be consumed at all, this object will be root).

consume_stack(root, stack)

Resolve a stack of steps as far as it can be resolved according to registered patterns, then stop resolving the stack. Does not throw a ResolutionError(), instead simply stops.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • stack (array) – A stack of steps, in reverse order from the path. It will be matched with the registered paths to find the lookup function.
Returns:

An object with three properties, unconsumed, an array of steps that could not be resolved (in stack form, reverse order), consumed, those steps that have been successfully consumed when resolving the path, and obj, the object found at the end of path consumption (if no stack could be consumed at all, this object will be root).

locate(root, obj)

Locate obj, giving it traject_name and traject_parent properties and placing it in a virtual hierarchy, such that following traject_parent will eventually result in the root object.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • obj (object) – The object to locate.

Can throw LocationError() in case the object can not be located.

path(root, obj)

Locate obj, and return its path. This also gives the obj traject_name and traject_parent properties and places it in a virtual hierarchy, such that following traject_parent will eventually result in the root object.

Arguments:
  • root (object) – An object that is the root to the virtual hierarchy created by traject. When following traject_parent back you will end up at the root object.
  • obj (object) – The object to get the path for.
Returns:

The path for obj according to the patterns.

Can throw LocationError() in case the object can not be located.