Obviel API

Obviel core

obviel.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.

obviel.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.

obviel.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.
obviel.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.

obviel.clearTemplateCache()

Clear the template cache from any cached templates. Useful to do as cleanup between unit test.

class obviel.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 obviel.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.

obviel.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.
obviel.unregisterView(iface, name)

Unregister view with Obviel. Obviel will forget about the view again. This is particularly useful during test cleanup, not during normal application running-time.

Arguments:
  • iface (string) – the iface of the view you want to unregister.
  • name (string) – the name of the view you want to unregister. Optional; the default name is default.
obviel.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.

obviel.eventHook(hook)
Arguments:
  • hook – a function with the signature function().

Register an event hook function with Obviel. Obviel will call this hook whenever an event is handled by Obviel Template. By default the event hook does nothing. This can be used in combination with Obviel Sync to automatically commit the session in event handlers.

You can disable the event hook by passing in null.

obviel.httpErrorHook(hook)
Arguments:
  • hook – a function with the signature function(xhr) where xhr is a jqXHR object as in use with jQuery $.ajax.

Register a hook function that gets called whenever an jQuery $.ajax call fails during rendering (though not during template load). This is the case when calling render on a URL, in subviews which call render on a URL, using the form validation URL, and the autocomplete form widget which uses a URL to receive autocomplete data.

element.render(obj[, name])

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 obviel.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.
Returns:

A promise. You can hook in a function to be called when rendering has completed, such as $(el).render(obj).done(function(view) { });

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.

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

    looked up.

element.rerender()

Re-render (non-ephemeral) view on element.

Returns:A promise. You can hook in a function to be called when rendering has completed, such as $(el).render(obj).done(function(view) { });. view will be null in case there was no view on this element to rerender.

If there is a previous view on the element, and the view was rendered from an object, the object is re-rendered on the element.

If there is a previous view on the element and the view was rendered from a URL, the object for the URL is re-fetched and then rendered.

If there is no previous view on the element, nothing will happen.

element.view()

Get the (non-epheremal) view previously rendered on element.

Returns:The non-ephemeral view previously rendered on the element. If no non-ephemeral view was rendered on the element, undefined is returned.
element.parentView()

Get nearest view registered on element or parent.

Returns:The non-ephemeral view rendered on element, or if missing, walk up the ancestor chain until a view is found. If no view can be found return null.
element.unview()

Remove non-ephemeral view from element, executing any view cleanup. If no view exists on this element, nothing happens.

View options

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

class obviel.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 obviel.view.render() function is called.

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

htmlUrl

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.

obvt

A string with an Obviel template that should be rendered on the view element. This will be done before any obviel.view.render() function is called.

This property is optional.

obvtUrl

A URL referencing a resource that is a Obviel template. This template will be loaded if the URL has not been previously seen, otherwise it is retrieved from a cache. The template is then rendered on the view element, combined with the object being viewed.

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.

jsontUrl

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.

objectEvents

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.

domain

The translation domain to use for any associated Obviel Template. If no domain is specified, the current translation domain specified by obviel.i18n.translate() is used.

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 obviel.template.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 obviel.template.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.

obviel.template.registerFormatter(name, func)

Register a global formatter. Is done when the UI starts up (per page), before any templates are compiled. Note that with Obviel you can also use view methods as formatters.

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

Return a global formatter. If no formatter can be found, undefined is returned.

Arguments:
  • name (string) – the name of the formatter to look up.
Returns:

the formatter function or undefined.

obviel.template.clearFormatters()

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

obviel.template.registerFunc(name, func)

Register a global element adjustment function. Is done when the UI starts up (per page), before any templates are compiled. Note that with Obviel you can use view methods as funcs

Arguments:
  • name (string) – the name of the function. This is how it is addressed in the template language (using data-call="funcName").
  • 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 context 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(variableName)).
obviel.template.getFunc(name)

Return a global element adjustment function. If no func can be found, undefined is returned.

Arguments:
  • name (string) – the name of the func to look up.
Returns:

the func or undefined.

obviel.template.clearFuncs()

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

class obviel.template.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, or alternatively a jQuery selector indicating an element to be compiled (everything in it will be compiled).

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

render(el, obj, context)

Render template on jQuery element el, using obj to resolve variables, and using context as the rendering context.

Arguments:
  • el (object) – jQuery element to render the template on.
  • obj (object) – Object to render. Variables in the templates will be resolved from obj.
  • context (object) –

    This is an object that may have these properties:

    getTranslation
    A function that takes a single string argument and returns the translation for that string. If no translation is available the string itself should be returned. If not supplied no translations are looked up. Used by data-trans.
    getHandler
    A function that gets a single name argument and returns the event handler that matches that name. If no handler can be found by that name, null should be returned. Used by data-on.
    getFormatter
    A function that gets a single name argument and returns the formatter function that matches that name. This function will get a single value argument and should return the formatted value. If no formatter can be found by that name, null or undefined should be returned. Used by {variable|formatter}. If no getFormatter is supplied, the template engine will use globally registered formatters (using obviel.template.registerFormatter). See also obviel.template.registerFormatter().
    getFunc
    A function that gets a single name argument and returns the element manipulation function that matches that name. This function will get three arguments: the element to manipulate, a variable lookup function and a context. If no func can be found by that name, null or undefined should be returned. Used by data-call to look up the func. If no getFunc is supplied, the template engine will use globally registred funcs (using obviel.template.registerFunc). See also obviel.template.registerFunc().
Returns:

A promise, so you can hook in .done(function()) { } that will be called when the template is done rendering.

obviel.template.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.

obviel.template.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 obviel.forms.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.

validationUrl

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 globalErrors 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.

globalErrors

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 obviel.forms.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 obviel.forms.InputWidget()

iface: inputField

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.

maxLength

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 obviel.forms.TextLineWidget()

iface: textlineField

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.minLength

The minimum input length in characters allowed.

validate.maxLength

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 obviel.forms.TextWidget()

iface: textField

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 obviel.forms.IntegerWidget()

iface: integerField

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.allowNegative

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 obviel.forms.FloatWidget()

iface: floatField

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.allowNegative

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

class obviel.forms.DecimalWidget()

iface: decimalField

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.allowNegative

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

validate.minBeforeSep

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

validate.maxBeforeSep

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

validate.minAfterSep

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

validate.maxAfterSep

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

class obviel.forms.BooleanWidget()

iface: booleanField

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 obviel.forms.ChoiceWidget()

iface: choiceField

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().

emptyOption

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 obviel.forms.DisplayWidget()

iface: displayField

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 obviel.forms.HiddenWidget()

iface: hiddenField

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

Derives from DisplayWidget()

class obviel.forms.DatePickerWidget()

iface:: datepickerField

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 obviel.forms.AutocompleteWidget()

iface:: autocompleteField

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('customField', 'inputField')

// constructor
module.CustomWidget = function(settings) {
   settings = settings || {};
   var d = {
       iface: 'customField' // 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 convertBack 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.convertBack = function(value) {
  // super call
  value = module.InputWidget.prototype.convertBack.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 obviel.traject namespace.

class obviel.traject.ParseError()

A parse error when parsing a path.

message

The error message.

class obviel.traject.ResolutionError()

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

message

The error message.

class obviel.traject.LocationError()

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

message

The error message.

class obviel.traject.RegistrationError()

Error during registration.

message

The error message.

class obviel.traject.Patterns()
registerConverter(converterName, converterFunc)

Register a variable converter.

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

Register a lookup function for a path pattern.

Arguments:
  • patternStr (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.

registerInverse(iface, patternStr, 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.
  • patternStr (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, patternStr, 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.
  • patternStr (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.

setDefaultLookup(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 trajectParent 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.

resolveStack(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 trajectParent 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 trajectParent 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).

consumeStack(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 trajectParent 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 trajectName and trajectParent properties and placing it in a virtual hierarchy, such that following trajectParent 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 trajectParent 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 trajectName and trajectParent properties and places it in a virtual hierarchy, such that following trajectParent 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 trajectParent 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.

Obviel i18n

Everything is in the obviel.i18n namespace.

class obviel.i18n.I18nError()

Exception. Something went wrong during translation; in particular a locale or domain cannot be found.

message

Message describing what went wrong.

obviel.i18n.translationSource(data)

Create a source of translations from mapping.

Arguments:
  • data (object) – A mapping from the language used in the source code to the language being translated to. Alternatively can use a more complicated jsgettext array structure as values.
Returns:

The translation source.

obviel.i18n.translationSourceFromJsonUrl(url)

Create a source of translations from a URL.

Arguments:
  • url (string) – A URL to a JSON object that contains a jsgettext-based translation.
Returns:

The translation source.

obviel.i18n.emptyTranslationSource()

Create an empty source of translations. This means no translation will take place. This can be useful to register the translations for the locale that the UI is written in.

Returns:The translation source.
obviel.i18n.registerTranslation(locale, translationSource[, domain])

Register a translation source for a locale and a domain.

Arguments:
  • locale (string) – A locale identifier, such as en_US.
  • translation_source – A translation source.
  • domain – The i18n domain for the translations. If domain is not specified, the default domain is used.
obviel.i18n.clearTranslations()

Clear the translations. Useful during test teardown.

obviel.i18n.setLocale(locale)

Changes the locale that the application is working in to a new one. This loads the locale information according to previously specified information, for instance using obviel.i18n.load().

Arguments:
  • locale (string) – A locale identifier, such as en_US.
Returns:

A promise that is done when the locale has been loaded.

obviel.i18n.clearLocale()

Clears the locale that the application is working in to an empty one. Useful during test teardown.

obviel.i18n.getLocale()

Returns the current locale. This is null if no locale has been set.

obviel.i18n.getTranslation(msgid, domain)

Gives back the translation for a msgid in a particular domain, given the current locale.

Arguments:
  • msgid (string) – The message id or text to translate.
  • domain (string) – The translation domain.
Returns:

The translation for msgid in the domain.

obviel.i18n.getTranslationFunc(domain)

Gives back a function that takes the msgid and returns the translation in the domain.

Arguments:
  • domain (string) – The translation domain.
Returns:

A function that can be given a msgid to return the translation in the specified domain.

obviel.i18n.translate(domain)

Set up translations for a module. Intended to be called at the top of your module, like this:

var _ = obviel.i18n.translate('foo');

This changes the template domain to foo, and also returns a function that when called with a message id, will return the translation in the domain foo. The convention is to assign this to _ so that extraction tools can extract occurrences from .js source code.

Arguments:
  • domain (string) – The translation domain.
Returns:

A function that can be given a msgid to return the translation in the specified domain and current locale.

obviel.i18n.pluralize(domain)

Set up plural translations for a module. Intended to be called at the top of your module, like this:

var ngettext = obviel.i18n.translate('foo');

The ngettext function can be called with three parameters:

  • singular text (“1 elephant”)
  • plural text (“three elephants”)
  • count

Based on the value of count either the singular text or plural text will be used, and translated to the current locale and the specified domain (foo, in this case).

Arguments:
  • domain (string) – The translation domain.
Returns:

A function that can be given a singular msgid, a plural msgid and a count and will return the right text for the locale, domain and count.

obviel.i18n.getTemplateDomain()

Gives back the default domain in use by Obviel templates.

obviel.i18n.variables(translation, variables)

An alias for obviel.template.variables(). Only available if Obviel Template is available when Obviel i18n is being loaded.

obviel.i18n.load()

Load i18n information as indicated by link elements in document. This should be called when the document is ready.

The link tags should look like this:

<link href="something.i18n" ref="i18n" type="application/json" />

The .i18n file indicated is a JSON file that describes what translations are available for which domains. You can link in multiple .i18n files in one page. The .i18n file should look like this:

{
   "<domain>": [
       {
         "locale": "<locale>",
         "url": "<localeUrl>"
       }
   ]
}

A domain may have information about more than one locale. The .i18n file may have entries for more than one domain. The url entry may be a relative URL, relative to the URL of the .i18n file itself. url may also be null, in which case the locale will not have any translations available and thus will be in the source language.

Returns:A promise that is done when the i18n information has been loaded. Recommended is you do the obviel.i18n.setLocale() in the done handler.