Class: View

just.View(optionsnullable)

Templarize elements easily.
Source:
just.js, line 3459

Parameters:

NameTypeDescription
options
[nullable]
objectAny just.View property.

Properties

NameTypeDefaultDescription
id
just.View#idUse either this or element.
element
just.View#elementUse either this or id.
data
just.View#dataData available on all updates for this view.
attributes
[optional]
string or just.View#attributesdata-varSet it to a string to use it as a prefix or set it to an object with this properties.

Example

Example 1: Generate elements based on one element.
<html>
<body>
  <ol>
    <li
      id='item'
      class='template'
      data-var-for='item in items as data-item'
      data-item-if='visible'
      hidden>
      <span
        data-item='${loop.index}. ${capitalize(item.text)} is visible!'
        data-item-attr='{
          "title": "Updated: ${updated}."
        }'></span>
    </li>
  </ol>
  <script src='/just.js'></script>
  <script>
    var view = new just.View({
      id: 'item',
      data: {
        capitalize: function (string) { return string[0].toUpperCase() + string.slice(1).toLowerCase(); },
        items: [{
          visible: true,
          text: 'first item'
        }, {
          visible: false,
          text: 'second item'
        }, {
          visible: true,
          text: 'third item'
        }]
      }
    });

    // Do some work...

    view.refresh({
      updated: new Date().toString()
    });
  </script>
</body>
</html>

Members

globals :object

Data available for all instances of just.View.
Source:
just.js, line 3540
Type:

object

INIT_ATTRIBUTE_NAME :string

Default attribute to query elements in just.View.init.
Source:
just.js, line 3533
Type:

string

attributes :object

Updatable attributes. I.e: attributes that will be updated when just.View#update gets called.
Source:
just.js, line 3499
Properties:
NameTypeDefaultDescription
var
[optional]
string${prefix}The attribute for text replacements.
html
[optional]
string${prefix}-htmlThe attribute for html replacements.
attr
[optional]
string${prefix}-attrThe attribute for attribute replacements.
if
[optional]
string${prefix}-ifThe attribute for conditional/if replacements.
as
[optional]
string${prefix}-asThe attribute for alias replacements. Scoping is not supported yet.
for
[optional]
string${prefix}-forThe attribute for loops replacements. Only arrays are supported now.
on
[optional]
string${prefix}-onThe attribute for listener replacements.
Type:

object

data :object

Data for this instance. Available on all updates.
Source:
just.js, line 3481
Type:

object

element :Node

The template element.
Source:
just.js, line 3476
Type:

Node

id :string

Id for the template element.
Source:
just.js, line 3471
Type:

string

original :object

Original properties for this instance.
Source:
just.js, line 3522
Type:

object

previousData :object

Previous data set after a just.View#update.
Source:
just.js, line 3515
Type:

object

Methods

attachListeners(element, datanon-null, attributeNamenon-null) → {object}

Parse an attribute as a json and set keys as event names/types and values as listeners. Values are accessable properties that require a function as final value.
Source:
just.js, line 3682
Parameters:
NameTypeDescription
element
NodeThe target element.
data
objectData for the accessable properties, containing the listeners.
attributeName
stringName of the attribute that contains the parseable json.
Returns:
The attached listeners, with event.types as keys.
Type
object

getAliases(element, datanullable, attributeNamenullable) → {object}

Define aliases using a stringified JSON from an element attribute; access object values and set keys as alias.
Source:
just.js, line 3996
Parameters:
NameTypeDescription
element
ElementThe target element.
data
[nullable]
objectSome object.
attributeName
[nullable]
stringThe name for attribute containing a stringified json.
Returns:
An object containing keys as alias.
Type
object

init(options) → {Array.<View>}

Find elements with the just.View.INIT_ATTRIBUTE_NAME attribute, parse its value as json, and call just.View with those options.
Source:
just.js, line 3644
Parameters:
NameTypeDescription
options
object
Properties
NameTypeDescription
listeners
objectListeners for the View#attachListeners call.
Returns:
The created views.
Type
View[]
Example
Example 1: Generate elements based on one element using minimum javascript.
<html>
<body
    data-just-View='{"element": ${this}}'
    data-var-on='{"init": "onInit"}'>
  <ol>
    <li
      id='item'
      class='template'
      data-var-for='item in items as data-item'
      data-item-if='visible'
      data-just-View='{
        "element": ${this},
        "data": {
          "items": [{
            "visible": true,
            "text": "first item"
          }, {
            "visible": false,
            "text": "second item"
          }, {
            "visible": true,
            "text": "third item"
          }]
        }
      }'
      hidden>
      <span
        data-item='${loop.index}. ${capitalize(item.text)} is visible!'
        data-item-attr='{
          "title": "Updated: ${updated}."
        }'></span>
    </li>
  </ol>
  <script src='/just.js'></script>
  <script>
    just.View.init({
      listeners: {
        onInit: function (e) {
          // This will refresh all [data-var] attributes.
          this.view.refresh(e.detail);
        }
      }
    });

    // Trigger the "init" event:
    document.body.dispatchEvent(
      new CustomEvent('init', {
        detail: {
          updated: new Date().toString()
        }
      })
    );
  </script>
</body>
</html>

replaceVars(value, datanullable, defaultValue) → {string}

Replace placeholders (${}, eg. ${deep.deeper}) within a string.
Source:
just.js, line 3819
Parameters:
NameTypeDescription
value
string or objectSome text or an object. If an object is given, it will just.View.resolveConditionals first, then replace ${placeholders} within the accessed value.
data
[nullable]
objectAn object containing the data to be replaced.
defaultValue
AnyBy default, it skips replacements if some accessed value is undefined. Any other value will be stringified (returned to the String#replace function).
Returns:
The replaced string. If some value is undefined, it won't be replaced at all.
Type
string
Examples
Example 1: Using a string
just.View.replaceVars('${splitted.property}!', {
    'splitted': {'property': 'hey'}
}); // > "hey!"
Example 2: Using an object
just.View.replaceVars({
    'a': 'Show ${a}',
    'b': 'Show ${b}'
}, {'b': 'me (b)'}); // > "Show me (b)"
Example 3: Inexistent property
just.View.replaceVars("Don't replace ${me}!") // "Don't replace ${me}!"
Example 4: Setting a default value for an inexistent property
just.View.replaceVars('Replace ${me}', null, 'who?') // "Replace who?"

resolveConditional(condititionalnullable) → {*|boolean}

Access to an object and return its value.
Source:
just.js, line 3726
Parameters:
NameTypeDescription
condititional
[nullable]
stringExpected keys splitted by ".". Use "!" to negate a expression. Use "true" to return true.
Returns:
if the conditional is negated, a boolean. Else, the accessed value.
Type
Any or boolean

resolveConditionals(conditionals, datanullable) → {*}

Access to multiple conditionals and return the first value that is truthy.
Source:
just.js, line 3751
Parameters:
NameTypeDescription
conditionals
object or stringAn object containing conditions (expected properties) as keys, or a string containing a condition (a expected property).
data
[nullable]
objectAn object with all the properties.
Returns:
View.resolveConditional()'s returned value.'
Type
Any

updateAttributes(element, datanullable, attributeNamenullable) → {boolean}

Create dynamic attributes after replacing variables in values. Please note that null/undefined values won't be replaced.
Source:
just.js, line 3963
Parameters:
NameTypeDescription
element
ElementThe target element.
data
[nullable]
objectSome object.
attributeName
[nullable]
stringThe name for attribute containing a stringified json.
Returns:
true if the attribute contains some value, false otherwise.
Type
boolean

updateConditionals(element, datanullable, attributeName) → {boolean}

Show/Hide an element (by setting/removing the [hidden] attribute) after evaluating the conditional found in the given attribute.
Source:
just.js, line 3935
Parameters:
NameTypeDescription
element
ElementThe target element.
data
[nullable]
objectSome object.
attributeName
stringThe name for the queried attribute.
Returns:
True if resolved (and hidden), false otherwise.
Type
boolean

updateHtmlVars(element, datanullable, attributeNamenullable) → {boolean}

Update the element's markup using just.View.updateVars and element.innerHTML.
Source:
just.js, line 3913
Parameters:
NameTypeDescription
element
ElementThe target element.
data
[nullable]
objectSome object.
attributeName
[nullable]
stringThe name for the queried attribute.
Returns:
true if the value was updated, false otherwise.
Type
boolean

updateLoops(element, data, attributeName) → {Array.<View>}

Iterate over an array to create multiple elements based on a given template (element), append them in order, and update each generated element.
Source:
just.js, line 4078
Parameters:
NameTypeDescription
element
NodeThe target element.
data
ObjectThe data.
attributeName
stringThe attribute containing the loop expression.
Returns:
The updated views or null.
Type
View[]

updateVars(element, datanullable, attributeNamenullable, setteropt, nullable) → {boolean}

Update the element's text if the attribute's value is different from the accessed value.
Source:
just.js, line 3877
Parameters:
NameTypeDefaultDescription
element
ElementThe target element.
data
[nullable]
objectSome object.
attributeName
[nullable]
stringThe name for the queried attribute.
setter
[optional] [nullable]
just.View~updateVars_setterelement.textContentIf set, a function to update the element's text. Expects a boolean to be returned. Else, element.textContent will be used to set the updated value and return true.
Returns:
true if the value was updated, false otherwise. Any other value will be casted to a Boolean.
Type
boolean

append(containernullable)

Call just.View#insert to perform an append of the current template element.
Source:
just.js, line 4403
Parameters:
NameTypeDescription
container
[nullable]
Node

attachListeners(listenersnullable)

Source:
just.js, line 4440
Parameters:
NameTypeDescription
listeners
[nullable]
objectAn object in the format: {eventType: fn}.

create()

Create a clone of an element, remove the .template class, the [hidden] attribute, and the [id] after setting it as a class on the clon. Set just.View#element to the new clon and return the current instance.
Source:
just.js, line 4275
Throws:
if the template is not a Node.
Type
TypeError

getData(currentDatanon-null) → {object}

Merges all available data into one object in the following order: just.View.globals, just.View#data, currentData, and aliases.
Source:
just.js, line 4219
Parameters:
NameTypeDescription
currentData
objectIt merges this object after globals, and locals, and before setting aliases.
Returns:
Type
object

getElement()

Source:
just.js, line 4207
Returns:
just.View#element or query element by just.View#id.

getUpdatables(container|documentopt, nullable) → {Array.<Node>}

Find all elements that contain a supported attribute and return them.
Source:
just.js, line 4246
Parameters:
NameTypeDescription
container|document
[optional] [nullable]
Node
Returns:
All matching elements within the given container
Type
Node[]

insert(position, containernullable)

Insert just.View#element at the given position into the given container.
Source:
just.js, line 4380
Parameters:
NameTypeDescription
position
string or object.<{before: Node}>- "before" will insert the element before the first child. - {"before": Node} will insert the element before the given Node. - else (other values): will use appendChild() by default.
container
[nullable]
NodeThe Node that will contain the element.
Throws:
if a container can't be guessed.
Type
TypeError

prepend(containernullable)

Call just.View#insert to perform an prepend of the current template element, at the beginning.
Source:
just.js, line 4414
Parameters:
NameTypeDescription
container
[nullable]
Node

refresh(newData, skip)

Update the view using just.View#previousData (set on update) and newData. Useful to update the view with previous values or update only some properties, after a normal update.
Source:
just.js, line 4357
Parameters:
NameTypeDescription
newData
AnyAny new data.
skip
just.View#update~skipskip argument.

reset()

Restore constructor to its default value. Use the #original property to restore it.
Source:
just.js, line 4425

update(data, skipnullable)

Update all updatable elements by querying them and calling all possible update* functions, like: - just.View.updateConditionals. - just.View.updateAttributes. - just.View.updateHtmlVars. - just.View.updateVars. - just.View.updateLoops. (In that order).
Source:
just.js, line 4311
Parameters:
NameTypeDescription
data
AnyData for the update. Merged with just.View#getData().
skip
[nullable]
functionA function called on each updatable element. if a truthy value is returned, the update won't take place.

Type Definitions

updateLoops_expression

Expression in the format: "currentItem in accessed.array[ as updatableAttribute][,[ cache=true]]".

Where text enclosed in brackets is optional, and:

  • currentItem is the property containing the current iteration data.
  • accessed.array is a property to be accessed that contains an array as value.
  • updatableAttribute is the name of the attribute that will be updated afterwards by View#update.
  • Setting cache will update existing elements, using each element as template. By default, this is true because it improves performance, but it also means that new modifications to each element will be replicated. If you set this to false, all generated elements will be removed before updating them, causing new modifications to be removed, but also hurting performance.
Source:
just.js, line 4017
Type:

string

Examples
Example 1.
"item in some.items"
// Will iterate over `some.items`, set `item` to each element (some.items[0], some.items[1], and so on...), and make `item` available under the default attribute.
Example 2.
"item in some.items as data-item"
// Will iterate over `some.items`, set `item` to each element, and make `item` available under the [data-item] attribute only.
Example 3.
"item in some.items as data-item, cache=false"
// Will iterate over `some.items`, set `item` to each element, make `item` available under the [data-item] attribute only, and recreate each element instead of updating it.

updateLoops_loopData

Loop data. Contains loop data for the current iteration.
Source:
just.js, line 4046
Properties:
NameTypeDescription
index
numberThe current index.
array
arrayThe array.
length
numberThe array's length.
left
numberLeft elements' count.
Type:

object

access(keys, datanullable)

Access to properties using the dot notation. Supports nested function arguments replacements and reserved keywords. See just.View~parseArguments.
Source:
just.js, line 3300
Parameters:
NameTypeDescription
keys
stringAccessable properties using the dot notation.
data
[nullable]
objectAccessable data.
Example
access('a.b(c(d))', {
  'a': {'b': function (v) { return v + 'b'; }},
  'c': function (v) { return v + 'c'; },
  'd': 'd'
}); // > 'dcb';

parseArguments(string, data) → {Array}

Parse argument-like strings ("a, b, c") and return valid JSON values.
Source:
just.js, line 3227
Parameters:
NameTypeDescription
string
stringArgument-like string without quotes, like "a, b, c".
data
objectAccessable data.
Returns:
Arguments.
Type
Array
Example
parseArguments("a, b, c", {})

updateVars_setter(element, text) → {boolean}

A function to set the updated value.
Source:
just.js, line 3854
Parameters:
NameTypeDescription
element
ElementThe target element.
text
stringThe updated text.
Returns:
true if updated, false otherwise.
Type
boolean