extend(obj, objects)

Description

Copies properties from all provided objects into the first object parameter

Arguments

ParamType(s)Description
objObject
objects...Object

Returns

Object

each(collection, callback, [thisArg])

Description

Iterates over the collection

Arguments

ParamType(s)Description
collectionArray ObjectThe array or object to iterate over
callbackFunctionThe callback that will be executed for each element in the collection
[thisArg]*Optional this context for the callback

Examples

blocks.each([3, 1, 4], function (value, index, collection) {
  // value is the current item (3, 1 and 4)
  // index is the current index (0, 1 and 2)
  // collection points to the array passed to the function - [3, 1, 4]
});

eachRight(collection, callback, [thisArg])

Description

Iterates over the collection from end to start

Arguments

ParamType(s)Description
collectionArray ObjectThe array or object to iterate over
callbackFunctionThe callback that will be executed for each element in the collection
[thisArg]*Optional this context for the callback

Examples

blocks.eachRight([3, 1, 4], function (value, index, collection) {
  // value is the current item (4, 1 and 3)
  // index is the current index (2, 1 and 0)
  // collection points to the array passed to the function - [3, 1, 4]
});

isArray(value)

Description

Determines if a value is an array. Returns false for array like objects (for example arguments object)

Arguments

ParamType(s)Description
value*The value to check if it is an array

Returns

boolean Whether the value is an array

Examples

blocks.isArray([1, 2, 3]);
// -> true

function calculate() {
  blocks.isArray(arguments);
  // -> false
}

noop()

Description

Represents a dummy empty function

Returns

Function Empty function

Examples

function max(collection, callback) {
  callback = callback || blocks.noop;
}

type(value)

Description

Determines the true type of an object

Arguments

ParamType(s)Description
value*The value for which to determine its type

Returns

string Returns the type of the value as a string

Examples

blocks.type('a string');
// -> string

blocks.type(314);
// -> number

blocks.type([]);
// -> array

blocks.type({});
// -> object

blocks.type(blocks.noop);
// -> function

blocks.type(new RegExp());
// -> regexp

blocks.type(undefined);
// -> undefined

blocks.type(null);
// -> null

is(value, type)

Description

Determines if a specific value is the specified type

Arguments

ParamType(s)Description
value*The value
typestringThe type

Returns

boolean If the value is from the specified type

Examples

blocks.is([], 'array');
// -> true

blocks.is(function () {}, 'object');
// -> false

has(obj, key)

Description

Checks if a variable has the specified property. Uses hasOwnProperty internally

Arguments

ParamType(s)Description
obj*The object to call hasOwnPrototype for
keyStringThe key to check if exists in the object

Returns

boolean Returns if the key exists in the provided object

Examples

blocks.has({
  price: undefined
}, 'price');
// -> true

blocks.has({
  price: 314
}, 'ratio');
// -> false

unwrap(value)

Description

Unwraps a jsblocks value to its raw representation. Unwraps blocks.observable() and blocks() values

Arguments

ParamType(s)Description
value*The value that will be unwrapped

Returns

* The unwrapped value

Examples

blocks.unwrap(blocks.observable(314));
// -> 314

blocks.unwrap(blocks([3, 1, 4]));
// -> [3, 1, 4]

blocks.unwrap('a string or any other value will not be changed');
// -> 'a string or any other value will not be changed'

toArray(value)

Description

Converts a value to an array. Arguments object is converted to array and primitive values are wrapped in an array. Does nothing when value is already an array

Arguments

ParamType(s)Description
value*The value to be converted to an array

Returns

Array The array

Examples

blocks.toArray(3);
// -> [3]

function calculate() {
  var numbers = blocks.toArray(arguments);
}

blocks.toArray([3, 1, 4]);
// -> [3, 1, 4]

toUnit(value, [unit='px'])

Description

Converts an integer or string to a unit. If the value could not be parsed to a number it is not converted

Arguments

ParamType(s)Description
value[type]The value to be converted to the specified unit
[unit='px']StringOptionally provide a unit to convert to. Default value is 'px'

Examples


 blocks.toUnit(230);
 // -> 230px

 blocks.toUnit(230, '%');
 // -> 230%

 blocks.toUnit('60px', '%');
 // -> 60%

clone(value, [deepClone])

Description

Clones value. If deepClone is set to true the value will be cloned recursively

Arguments

ParamType(s)Description
value*
[deepClone]booleanDescription

Returns

* Description

Examples

var array = [3, 1, 4];
var cloned = blocks.clone(array);
// -> [3, 1, 4]
var areEqual = array == cloned;
// -> false

isElements(value)

Description

Determines if the specified value is a HTML elements collection

Arguments

ParamType(s)Description
value*The value to check if it is elements collection

Returns

boolean Returns whether the value is elements collection

isElement(value)

Description

Determines if the specified value is a HTML element

Arguments

ParamType(s)Description
value*The value to check if it is a HTML element

Returns

boolean Returns whether the value is a HTML element

Examples

blocks.isElement(document.body);
// -> true

blocks.isElement({});
// -> false

isBoolean(value)

Description

Determines if a the specified value is a boolean.

Arguments

ParamType(s)Description
value*The value to be checked if it is a boolean

Returns

boolean Whether the value is a boolean or not

Examples

blocks.isBoolean(true);
// -> true

blocks.isBoolean(new Boolean(false));
// -> true

blocks.isBoolean(1);
// -> false

isObject(obj)

Description

Determines if the specified value is an object

Arguments

ParamType(s)Description
obj[type]The value to check for if it is an object

Returns

boolean Returns whether the value is an object

isPlainObject(obj)

Description

Determines if a value is a object created using {} or new Object

Arguments

ParamType(s)Description
obj*The value that will be checked

Returns

boolean Whether the value is a plain object or not

Examples

blocks.isPlainObject({ property: true });
// -> true

blocks.isPlainObject(new Object());
// -> true

function Car () {

}

blocks.isPlainObject(new Car());
// -> false

bind(func, thisArg, [args])

Description

Changes the this binding to a function and optionally passes additional parameters to the function

Arguments

ParamType(s)Description
funcFunctionThe function for which to change the this binding and optionally add arguments
thisArg*The new this binding context value
[args]...*Optional arguments that will be passed to the function

Returns

Function The newly created function having the new this binding and optional arguments

Examples

var alert = blocks.bind(function () {
  alert(this);
}, 'Hello bind method!');

alert();
// -> alerts 'Hello bind method'

var alertAll = blocks.bind(function (firstName, lastName) {
  alert('My name is ' + firstName + ' ' + lastName);
}, null, 'John', 'Doe');

alertAll();
// -> alerts 'My name is John Doe'

equals(a, b, [deepEqual])

Description

Determines if two values are deeply equal. Set deepEqual to false to stop recusively equality checking

Arguments

ParamType(s)Description
a*The first object to be campared
b*The second object to be compared
[deepEqual]booleanDetermines if the equality check will recursively check all child properties

Returns

boolean Whether the two values are equal

Examples

blocks.equals([3, 4], [3, 4]);
// -> true

blocks.equals({ value: 7 }, { value: 7, result: 1});
// -> false

query(model, [element=document.body])

Description

Performs a query operation on the DOM. Executes all data-query attributes and renders the html result to the specified HTMLElement if not specified uses document.body by default.

Arguments

ParamType(s)Description
model*The model that will be used to query the DOM.
[element=document.body]HTMLElementOptional element on which to execute the query.

Examples

<script>
  blocks.query({
    message: 'Hello World!'
  });
</script>
<h1>Hey, {{message}}</h1>

<!-- will result in -->
<h1>Hey, Hello World!</h1>

context(element)

Description

Gets the context for a particular element. Searches all parents until it finds the context.

Arguments

ParamType(s)Description
elementHTMLElement blocks.VirtualElementThe element from which to search for a context

Returns

Object The context object containing all context properties for the specified element

Examples

<script>
  blocks.query({
    items: ['John', 'Alf', 'Mega'],
    alertIndex: function (e) {
      alert('Clicked an item with index:' + blocks.context(e.target).$index);
    }
  });
</script>
<ul data-query="each(items)">
  <li data-query="click(alertIndex)">{{$this}}</li>
</ul>

dataItem(element)

Description

Gets the associated dataItem for a particlar element. Searches all parents until it finds the context

Arguments

ParamType(s)Description
elementHTMLElement blocks.VirtualElementThe element from which to search for a dataItem

Returns

*

Examples

<script>
  blocks.query({
    items: [1, 2, 3],
    alertValue: function (e) {
      alert('Clicked the value: ' + blocks.dataItem(e.target));
    }
  });
</script>
<ul data-query="each(items)">
  <li data-query="click(alertValue)">{{$this}}</li>
</ul>

isObservable(value)

Description

Determines if particular value is an blocks.observable

Arguments

ParamType(s)Description
value*The value to check if the value is observable

Returns

boolean Returns if the value is observable

Examples

blocks.isObservable(blocks.observable(3));
// -> true

blocks.isObservable(3);
// -> false

unwrapObservable(value)

Description

Gets the raw value of an observable or returns the value if the specified object is not an observable

Arguments

ParamType(s)Description
value*The value that could be any object observable or not

Returns

* Returns the unwrapped value

Examples

blocks.unwrapObservable(blocks.observable(304));
// -> 304

blocks.unwrapObservable(305);
// -> 305

if(condition, consequent, [alternate])

Description

Executes particular query depending on the condition specified

Arguments

ParamType(s)Description
conditionbooleanThe result will determine if the consequent or the alternate query will be executed
consequentdata-queryThe query that will be executed if the specified condition returns a truthy value
[alternate]data-queryThe query that will be executed if the specified condition returns a falsy value

Examples

<div data-query="if(true, setClass('success'), setClass('fail'))"></div>
<div data-query="if(false, setClass('success'), setClass('fail'))"></div>

<!-- will result in -->
<div data-query="if(true, setClass('success'), setClass('fail'))" class="success"></div>
<div data-query="if(false, setClass('success'), setClass('fail'))" class="fail"></div>

ifnot(condition, consequent, [alternate])

Description

Executes particular query depending on the condition specified. The opposite query of the 'if'

Arguments

ParamType(s)Description
conditionbooleanThe result will determine if the consequent or the alternate query will be executed
consequentdata-queryThe query that will be executed if the specified condition returns a falsy value
[alternate]data-queryThe query that will be executed if the specified condition returns a truthy value

Examples

<div data-query="ifnot(true, setClass('success'), setClass('fail'))"></div>
<div data-query="ifnot(false, setClass('success'), setClass('fail'))"></div>

<!-- will result in -->
<div data-query="ifnot(true, setClass('success'), setClass('fail'))" class="fail"></div>
<div data-query="ifnot(false, setClass('success'), setClass('fail'))" class="success"></div>

template(template, [value])

Description

Queries and sets the inner html of the element from the template specified

Arguments

ParamType(s)Description
templateHTMLElement stringThe template that will be rendered The value could be an element id (the element innerHTML property will be taken), string (the template) or an element (again the element innerHTML property will be taken)
[value]*Optional context for the template

Examples

<script>
  blocks.query({
    name: 'John Doe',
    age: 22
  });
</script>
<script id="user" type="blocks-template">
  <h3>{{name}}</h3>
  <p>I am {{age}} years old.</p>
</script>
<div data-query="template('user')">
</div>

<!-- will result in -->
<div data-query="template('user')">
  <h3>John Doe</h3>
  <p>I am 22 years old.</p>
</div>

define(propertyName, propertyValue)

Description

Creates a variable name that could be used in child elements

Arguments

ParamType(s)Description
propertyNamestringThe name of the value that will be created and you could access its value later using that name
propertyValue*The value that the property will have

Examples

<script>
  blocks.query({
    strings: {
      title: {
        text: 'Hello World!'
      }
    }
  });
</script>
<div data-query="define('$title', strings.title.text)">
  The title is {{$title}}.
</div>

<!-- will result in -->
<div data-query="define('$title', strings.title.text)">
  The title is Hello World!.
</div>

with(value, [name])

Description

Changes the current context for the child elements. Useful when you will work a lot with a particular value

Arguments

ParamType(s)Description
value*The new context
[name]stringOptional name of the new context This way the context will also available under the name not only under the $this context property

Examples

<script>
  blocks.query({
    ProfilePage: {
      user: {
        name: 'John Doe',
        age: 22
      }
    }
  });
</script>
<div data-query="with(ProfilePage.user, '$user')">
 My name is {{$user.name}} and I am {{$this.age}} years old.
</div>

<!-- will result in -->
<div data-query="with(ProfilePage.user, '$user')">
 My name is John Doe and I am 22 years old.
</div>

each(collection)

Description

The each method iterates through an array items or object values and repeats the child elements by using them as a template

Arguments

ParamType(s)Description
collectionArray ObjectThe collection to iterate over

Examples

<script>
  blocks.query({
    items: ['John', 'Doe']
  });
</script>
<ul data-query="each(items)">
  <li>{{$this}}</li>
</ul>

<!-- will result in -->
<ul data-query="each(items)">
  <li>John</li>
  <li>Doe</li>
</ul>

options(collection, [options])

Description

Render options for a <select> element by providing an collection.

Arguments

ParamType(s)Description
collectionArray ObjectThe collection to iterate over
[options]ObjectOptions to customize the behavior for creating each option. options.value - determines the field in the collection to server for the option value options.text - determines the field in the collection to server for the option text options.caption - creates a option with the specified text at the first option

Examples

<script>
blocks.query({
  caption: 'Select user'
  data: [
    { name: 'John', id: 1 },
    { name: 'Doe', id: 2 }
  ]
});
</script>
<select data-query="options(data, { text: 'name', value: 'id', caption: caption })">
</select>

<!-- will result in -->
<select data-query="options(data, { text: 'name', value: 'id', caption: caption })">
  <option>Select user</option>
  <option value="1">John</option>
  <option value="2">Doe</option>
</select>

render(condition, [renderChildren=false])

Description

The render query allows elements to be skipped from rendering and not to exist in the HTML result

Arguments

ParamType(s)Description
conditionbooleanThe value determines if the element will be rendered or not
[renderChildren=false]booleanThe value indicates if the children will be rendered

Examples

<div data-query="render(true)">Visible</div>
<div data-query="render(false)">Invisible</div>

<!-- html result will be -->
<div data-query="render(true)">Visible</div>

animate(callback)

Description

Could be used for custom JavaScript animation by providing a callback function that will be called the an animation needs to be performed

Arguments

ParamType(s)Description
callbackFunctionThe function that will be called when animation needs to be performed.

Examples

<script>
blocks.query({
  visible: blocks.observable(true),
  toggleVisibility: function () {
    // this points to the model object passed to blocks.query() method
    this.visible(!this.visible());
  },

  fade: function (element, ready) {
    Velocity(element, {
      // this points to the model object passed to blocks.query() method
      opacity: this.visible() ? 1 : 0
    }, {
      duration: 1000,
      queue: false,

      // setting the ready callback to the complete callback
      complete: ready
    });
  }
});
</script>
<button data-query="click(toggleVisibility)">Toggle visibility</button>
<div data-query="visible(visible).animate(fade)" style="background: red;width: 300px;height: 240px;">
</div>

setClass(className, [condition=true])

Description

Adds or removes a class from an element

Arguments

ParamType(s)Description
classNamestring ArrayThe class string (or array of strings) that will be added or removed from the element.
[condition=true]boolean undefinedOptional value indicating if the class name will be added or removed. true - add, false - remove.

Examples

<div data-query="setClass('header')"></div>

<!-- will result in -->
<div data-query="setClass('header')" class="header"></div>

html(html, [condition=true])

Description

Sets the inner html to the element

Arguments

ParamType(s)Description
htmlstringThe html that will be places inside element replacing any other content.
[condition=true]booleanCondition indicating if the html will be set.

Examples

<div data-query="html('<b>some content</b>')"></div>

<!-- will result in -->
<div data-query="html('<b>some content</b>')"><b>some content</b></div>

text(text, [condition=true])

Description

Adds or removes the inner text from an element. Escapes any HTML provided

Arguments

ParamType(s)Description
textstringThe text that will be places inside element replacing any other content.
[condition=true]booleanValue indicating if the text will be added or cleared. true - add, false - clear.

Examples

<div data-query="html('some content')"></div>

<!-- will result in -->
<div data-query="html('some content')">some content</div>

visible([condition=true])

Description

Determines if an html element will be visible. Sets the CSS display property.

Arguments

ParamType(s)Description
[condition=true]booleanValue indicating if element will be visible or not.

Examples

<div data-query="visible(true)">Visible</div>
<div data-query="visible(false)">Invisible</div>

<!-- html result will be -->
<div data-query="visible(true)">Visible</div>
<div data-query="visible(false)" style="display: none;">Invisible</div>

attr(attributeName, attributeValue)

Description

Gets, sets or removes an element attribute. Passing only the first parameter will return the attributeName value

Arguments

ParamType(s)Description
attributeNamestringThe attribute name that will be get, set or removed.
attributeValuestringThe value of the attribute. It will be set if condition is true.

Examples

<div data-query="attr('data-content', 'some content')"></div>

<!-- will result in -->
<div data-query="attr('data-content', 'some content')" data-content="some content"></div>

val(value)

Description

Sets the value attribute on an element.

Arguments

ParamType(s)Description
valuestring number Array undefinedThe new value for the element.

Examples

<script>
blocks.query({
  name: blocks.observable('John Doe')
});
</script>
<input data-query="val(name)">

<!-- will result in -->
<input data-query="val(name)" value="John Doe">

checked([condition=true])

Description

Sets the checked attribute on an element

Arguments

ParamType(s)Description
[condition=true]boolean undefinedDetermines if the element will be checked or not

Examples

<input type="checkbox" data-query="checked(true)">
<input type="checkbox" data-query="checked(false)">

<!-- will result in -->
<input type="checkbox" data-query="checked(true)" checked="checked">
<input type="checkbox" data-query="checked(false)">

disabled([condition=true])

Description

Sets the disabled attribute on an element

Arguments

ParamType(s)Description
[condition=true]boolean undefinedDetermines if the element will be disabled or not

css(name, value)

Description

Gets, sets or removes a CSS style from an element. Passing only the first parameter will return the CSS propertyName value.

Arguments

ParamType(s)Description
namestringThe name of the CSS property that will be get, set or removed
valuestringThe value of the of the attribute. It will be set if condition is true

Examples

<script>
  blocks.query({
    h1FontSize: 12
  });
</script>
<h1 data-query="css('font-size', h1FontSize)"></h1>
<h1 data-query="css('fontSize', h1FontSize)"></h1>

<!-- will result in -->
<h1 data-query="css('font-size', h1FontSize)" style="font-size: 12px;"></h1>
<h1 data-query="css('fontSize', h1FontSize)" style="font-size: 12px;"></h1>

width(value)

Description

Sets the width of the element

Arguments

ParamType(s)Description
valuenumber stringThe new width of the element

height(value)

Description

Sets the height of the element

Arguments

ParamType(s)Description
valuenumber stringThe new height of the element

on(events, callback, [args])

Description

Subscribes to an event

Arguments

ParamType(s)Description
eventsString ArrayThe event or events to subscribe to
callbackFunctionThe callback that will be executed when the event is fired
[args]*Optional arguments that will be passed as second parameter to the callback function after the event arguments

view(view)

Description

Associates the element with the particular view and creates a $view context property. The View will be automatically hidden and shown if the view have routing. The visibility of the View could be also controled using the isActive observable property

Arguments

ParamType(s)Description
viewViewThe view to associate with the current element

Examples

<!-- Associating the div element and its children with the Profiles view -->
<div data-query="view(Profiles)">
  <!-- looping through the View users collection -->
  <ul data-query="each(users)">
    <!-- Using the $view context value to point to the View selectUser handler -->
    <li data-query="click($view.selectUser)">{{username}}</li>
  </ul>
</div>
var App = blocks.Application();

App.View('Profiles', {
  users: [{ username: 'John' }, { username: 'Doe' }],

  selectUser: function (e) {
    // ...stuff...
  }
});

navigateTo(viewOrRoute, [params])

Description

Navigates to a particular view by specifying the target view or route and optional parameters

Arguments

ParamType(s)Description
viewOrRouteView Stringthe view or route to which to navigate to
[params]Objectparameters needed for the current route

Examples

<!-- will navigate to /contactus because the ContactUs View have /contactus route -->
<a data-query="navigateTo(ContactUs)">Contact Us</a>

<!-- will navigate to /products/t-shirts because the Products View have /products/{{category}} route -->
<a data-query="navigateTo(Products, { category: 't-shirts' })">T-Shirts</a>

<!-- the same example as above but the route is directly specifying instead of using the View instance -->
<a data-query="navigateTo('/products/{{category}}', { category: 't-shirts' })">T-Shirts</a>

reset(value)

Description

Removes all items from the collection and replaces them with the new value provided. The value could be Array, observable array or jsvalue.Array

Arguments

ParamType(s)Description
valueArrayThe new value that will be populated

Returns

blocks.observable Returns the observable itself - return this;

Examples

// creates an observable array with [1, 2, 3] as values
var items = blocks.observable([1, 2, 3]);

// removes the previous values and fills the observable array with [5, 6, 7] values
items.reset([5, 6, 7]);

add(value, [index])

Description

Adds values to the end of the observable array

Arguments

ParamType(s)Description
value*The values that will be added to the end of the array
[index]numberOptional index specifying where to insert the value

Returns

blocks.observable Returns the observable itself - return this;

Examples

var items = blocks.observable([1, 2, 3]);

// results in observable array with [1, 2, 3, 4] values
items.add(4);

addMany(value, [index])

Description

Adds the values from the provided array(s) to the end of the collection

Arguments

ParamType(s)Description
valueArrayThe array that will be added to the end of the array
[index]numberOptional position where the array of values to be inserted

Returns

blocks.observable Returns the observable itself - return this;

Examples

var items = blocks.observable([1, 2, 3]);

// results in observable array with [1, 2, 3, 4, 5, 6] values
items.addMany([4, 5], [6]);

swap(indexA, indexB)

Description

Swaps two values in the observable array. Note: Faster than removing the items and adding them at the locations

Arguments

ParamType(s)Description
indexAnumberThe first index that points to the index in the array that will be swapped
indexBnumberThe second index that points to the index in the array that will be swapped

Returns

blocks.observable Returns the observable itself - return this;

Examples

var items = blocks.observable([4, 2, 3, 1]);

// results in observable array with [1, 2, 3, 4] values
items.swap(0, 3);

move(sourceIndex, targetIndex)

Description

Moves an item from one location to another in the array. Note: Faster than removing the item and adding it at the location

Arguments

ParamType(s)Description
sourceIndexnumberThe index pointing to the item that will be moved
targetIndexnumberThe index where the item will be moved to

Returns

blocks.observable Returns the observable itself - return this;

Examples

var items = blocks.observable([1, 4, 2, 3, 5]);

// results in observable array with [1, 2, 3, 4, 5] values
items.move(1, 4);

remove(value, [thisArg])

Description

Removes an item from the observable array

Arguments

ParamType(s)Description
valueFunction *the value that will be removed or a callback function which returns true or false to determine if the value should be removed
[thisArg]FunctionOptional this context for the callback

Returns

blocks.observable Returns the observable itself - return this;

Examples

removeAt(index, [count])

Description

Removes an item at the specified index

Arguments

ParamType(s)Description
indexnumberThe index location of the item that will be removed
[count]numberOptional parameter that if specified will remove the next items starting from the specified index

Returns

blocks.observable Returns the observable itself - return this;

removeAll([callback], [thisArg])

Description

Removes all items from the observable array and optionally filter which items to be removed by providing a callback

Arguments

ParamType(s)Description
[callback]FunctionOptional callback function which filters which items to be removed. Returning a truthy value will remove the item and vice versa
[thisArg]*Optional this context for the callback function

Returns

blocks.observable Returns the observable itself - return this;

concat(arrays)

Description

The concat() method is used to join two or more arrays

Arguments

ParamType(s)Description
arrays...ArrayThe arrays to be joined

Returns

Array The joined array

slice(start, [end])

Description

The slice() method returns the selected elements in an array, as a new array object

Arguments

ParamType(s)Description
startnumberAn integer that specifies where to start the selection (The first element has an index of 0)
[end]numberAn integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array

Returns

Array A new array, containing the selected elements

join([seperator=','])

Description

The join() method joins the elements of an array into a string, and returns the string

Arguments

ParamType(s)Description
[seperator=',']stringThe separator to be used. If omitted, the elements are separated with a comma

Returns

string The array values, separated by the specified separator

pop()

Description

The pop() method removes the last element of a observable array, and returns that element

Returns

* The removed array item

push(values)

Description

The push() method adds new items to the end of the observable array, and returns the new length

Arguments

ParamType(s)Description
values...*The item(s) to add to the observable array

Returns

number The new length of the observable array

reverse()

Description

Reverses the order of the elements in the observable array

Returns

Array The array after it has been reversed

shift()

Description

Removes the first element of a observable array, and returns that element

Returns

* The removed array item

sort([sortfunction])

Description

Sorts the elements of an array

Arguments

ParamType(s)Description
[sortfunction]FunctionA function that defines the sort order

Returns

Array The Array object, with the items sorted

splice(index, howMany, The)

Description

Adds and/or removes elements from the observable array

Arguments

ParamType(s)Description
indexnumberAn integer that specifies at what position to add/remove items. Use negative values to specify the position from the end of the array.
howManynumberThe number of items to be removed. If set to 0, no items will be removed.
The...*new item(s) to be added to the array.

Returns

Array A new array containing the removed items, if any.

unshift(The)

Description

The unshift() method adds new items to the beginning of an array, and returns the new length.

Arguments

ParamType(s)Description
The...*new items that will be added to the beginning of the observable array.

Returns

number The new length of the observable array.

filter(options)

Description

Extends the observable by adding a .view property which is filtered based on the provided options

Arguments

ParamType(s)Description
optionsFunction Object Stringprovide a callback function which returns true or false, you could also provide an observable

Returns

blocks.observable Returns a new observable containing a .view property with the filtered data

skip(value)

Description

Extends the observable by adding a .view property in which the first n items are skipped

Arguments

ParamType(s)Description
valuenumber blocks.observableThe number of items to be skipped

Returns

blocks.observable Returns a new observable containing a .view property with the manipulated data

take(value)

Description

Extends the observable by adding a .view property in which there is always maximum n items

Arguments

ParamType(s)Description
valuenumber blocks.observable)The max number of items to be in the collection

Returns

blocks.observable Returns a new observable containing a .view property with the manipulated data

sort(options)

Description

Extends the observable by adding a .view property which is sorted based on the provided options

Arguments

ParamType(s)Description
optionsFunction stringprovide a callback sort function or field name to be sorted

Returns

blocks.observable Returns a new observable containing a .view property with the sorted data

update()

Description

Updates all elements, expressions and dependencies where the observable is used

Returns

blocks.observable Returns the observable itself - return this;

extend([name], [options])

Description

Extends the current observable with particular functionality depending on the parameters specified. If the method is called without arguments and jsvalue framework is included the observable will be extended with the methods available in jsvalue for the current type

Arguments

ParamType(s)Description
[name]String
[options]...*

Returns

* The result of the extend or the observable itself

Examples

blocks.observable.formatter = function () {
  // your code here
};

// extending using the formatter extender
var data = blocks.observable([1, 2, 3]).extend('formatter');

Property(property)

Description

Creates an application property for a Model

Arguments

ParamType(s)Description
propertyObjectAn object describing the options for the current property

Examples


 var App = blocks.Application();

 var User = App.Model({
   username: App.Property({
     defaultValue: 'John Doe'
   })
 });

Model(prototype)

Description

Creates a new Model

Arguments

ParamType(s)Description
prototypeObjectthe Model object properties that will be created

Returns

Model the Model type with the specified properties

Examples


 var App = blocks.Application();

 var User = App.Model({
  firstName: App.Property({
   required: true,
   validateOnChange: true
  }),

  lastName: App.Property({
   required: true,
   validateOnChange: true
  }),

  fullName: App.Property({
    value: function () {
      return this.firstName() + ' ' + this.lastName();
    }
  })
 });

 App.View('Profile', {
  user: User({
    firstName: 'John',
    lastName: 'Doe'
  })
 });
<div data-query="view(Profile)">
  <h3>
    FullName is: {{user.fullName()}}
  </h3>
</div>

<!-- will result in -->
<div data-query="view(Profile)">
  <h3>
    FullName is: John Doe
  </h3>
</div>

Collection(prototype)

Description

Creates a new Collection

Arguments

ParamType(s)Description
prototypeObjectThe Collection object properties that will be created.

Returns

Collection The Collection type with the specified properties

Examples


 var App = blocks.Application();

 var User = App.Model({
  firstName: App.Property({
   required: true,
   validateOnChange: true
  }),

  lastName: App.Property({
   required: true,
   validateOnChange: true
  }),

  fullName: App.Property({
    value: function () {
      return this.firstName() + ' ' + this.lastName();
    }
  })
 });

 var Users = App.Collection(User, {
   count: App.Property({
     value: function () {
       return this().length;
     }
   })
 });

 App.View('Profiles', {
  users: Users([{
     firstName: 'John',
     lastName: 'Doe'
   }, {
     firstName: 'Johna',
     lastName: 'Doa'
   }])
 });
<div data-query="view(Profiles)">
  <h2>Total count is {{users.count}}</h2>
  <ul data-query="each(users)">
    <li>
      FullName is: {{fullName()}}
    </li>
  </ul>
</div>

<!-- will result in -->
<div data-query="view(Profiles)">
  <h2>Total count is 2</h2>
  <ul data-query="each(users)">
    <li>
      FullName is: John Doe
    </li>
    <li>
      FullName is: Johna Doa
    </li>
  </ul>
</div>

View([parentViewName], name, prototype)

Description

Defines a view that will be part of the Application

Arguments

ParamType(s)Description
[parentViewName]stringProvide this parameter only if you are creating nested views. This is the name of the parent View
namestringThe name of the View you are creating
prototypeObjectThe object that will represent the View

Examples

var App = blocks.Application();

App.View('Clicker', {
  handleClick: function () {
    alert('Clicky! Click!');
  }
});

 <div data-query="view(Clicker)">
   <h3><a href="#" data-query="click(handleClick)">Click here!</a></h3>
 </div>

isActive()

Description

Determines if the view is visible or not. This property is automatically populated when routing is enabled for the view.

init()

Description

Override the init method to perform actions when the View is first created and shown on the page

Examples

var App = blocks.Application();

App.View('Statistics', {
  init: function () {
    this.loadRemoteData();
  },

  loadRemoteData: function () {
    // ...stuff...
  }
});

ready()

Description

Override the ready method to perform actions when the DOM is ready and all data-query have been executed.

Examples

var App = blocks.Application();

App.View('ContactUs', {
  ready: function () {
    $('#contact-form').ajaxSubmit();
  }
});

routed()

Description

Override the routed method to perform actions when the View have routing and routing mechanism actives it.

Examples

var App = blocks.Application();

App.View('ContactUs', {
  options: {
    route: 'contactus'
  },

  routed: function () {
    alert('Navigated to ContactUs page!')
  }
});

loading()

Description

Observable which value is true when the View html is being loaded using ajax request. It could be used to show a loading indicator.

parentView()

Description

Gets the parent view. Returns null if the view is not a child of another view.

route(name)

Description

Routes to a specific URL and actives the appropriate views associated with the URL

Arguments

ParamType(s)Description
nameString

Returns

View Chainable. Returns this

Examples

var App = blocks.Application();

App.View('ContactUs', {
  options: {
    route: 'contactus'
  }
});

App.View('Navigation', {
  navigateToContactUs: function () {
    this.route('contactus')
  }
});

options()

Description

The options for the Model

init()

Description

Override the init method to perform actions on creation for each Model instance

Examples

var App = blocks.Application();

var Product = App.Model({
  init: function () {
    this.finalPrice = this.price() * this.ratio();
  },

  price: App.Property({
    defaultValue: 0
  }),

  ratio: App.Property({
    defaultValue: 1
  })
});

validate()

Description

Validates all observable properties that have validation and returns true if all values are valid otherwise returns false

Returns

boolean Value indicating if the model is valid or not

Examples

var App = blocks.Application();

var User = App.Model({
  username: App.Property({
    required: true
  }),

  email: App.Property({
    email: true
  })
});

App.View('SignUp', {
  newUser: User(),

  registerUser: function () {
    if (this.newUser.validate()) {
      alert('Successful registration!');
    }
  }
});

dataItem()

Description

Extracts the raw(non observable) dataItem object values from the Model

Returns

Object Returns the raw dataItem object

Examples

var App = blocks.Application();
var User = App.Model({
  firstName: App.Property({
    defaultValue: 'John'
  })
});

App.View('Profile', {
  user: User(),

  init: function () {
    var dataItem = this.user.dataItem();
    // -> { firstName: 'defaultValue' }
  }
});

reset(dataItem)

Description

Applies new properties to the Model by providing an Object

Arguments

ParamType(s)Description
dataItemObjectThe object from which the new values will be applied

Returns

Model Chainable. Returns itself

isNew()

Description

Determines whether the instance is new. If true when syncing the item will send for insertion instead of updating it. The check is determined by the idAttr value specified in the options. If idAttr is not specified the item will always be considered new.

Returns

boolean Returns whether the instance is new

read([params])

Description

Fires a request to the server to populate the Model based on the read URL specified

Arguments

ParamType(s)Description
[params]ObjectThe parameters Object that will be used to populate the Model from the specified options.read URL. If the URL does not contain parameters

Returns

Model Chainable. Returns the Model itself - returns this;

sync([callback])

Description

Synchronizes the changes with the server by sending requests to the provided URL's

Arguments

ParamType(s)Description
[callback]FunctionOptional callback which will be executed when all sync operations have been successfully completed

Returns

Model Returns the Model itself - return this;

read([params])

Description

Fires a request to the server to populate the Model based on the read URL specified

Arguments

ParamType(s)Description
[params]ObjectThe parameters Object that will be used to populate the Collection from the specified options.read URL. If the URL does not contain parameters

Returns

Collection Chainable. Returns the Collection itself - return this;

Examples

var App = blocks.Application();

var Products = App.Collection({
  options: {
    read: {
      url: 'http://your-servrice-url/{{id}}'
    }
  }
});

var products = Products().read({
  // the id that will be replaced in the above options.read URL
  id: 3
});

clearChanges()

Description

Clear all changes made to the collection

Returns

Collection Chainable. Returns this

Examples

var App = blocks.Application();

var Products = App.Collection({

});

App.View('Products', function () {
  products: Products(),

  init: function () {
    this.products.push({
      ProductName: 'Fish'
    });

    // -> this.products.length = 1
    this.products.clearChanges();
    // -> this.products.length = 0
  }
});

sync([callback])

Description

Performs an ajax request for all create, update and delete operations in order to sync them with a database.

Arguments

ParamType(s)Description
[callback]FunctionOptional callback which will be executed when all sync operations have been successfully completed

Returns

Collection Chainable. Returns the Collection itself - return this;

Examples

var App = blocks.Application();
var Products = App.Collection({
  options: {
    create: {
      url: 'serviceURL/CreateProduct'
    }
  }
});

App.View('Products', function () {
  products: Products(),

  init: function () {
    this.products.push({
      ProductName: 'Fish'
    });

    // sends AJAX request to the create.url with the new item
    this.products.sync();
  }
});

update(id, newValues)

Description

Arguments

ParamType(s)Description
idnumber
newValuesObject

Returns

Collection Chainable. Returns the Collection itself - return this;