Every repository with this icon (
Every repository with this icon (
Javascript Functions as Directives
This example is about passing javascript functions references as directives.
There are 3 ways a function can be passed as a directive described after the example:
Other examples:
Basic
Iteration
Attributes
Nested loops
Functions
Recursion
| Player |
|---|
| Chloe |
In addition to the zebra iteration, this example shows a way to attach events by a directive.
To see those events in action, mouse-over the lines of the rendered table, and click on a line.
The HTML:
<table id="players2" class="players 2">
<thead>
<tr>
<th class="player">Player</th>
</tr>
</thead>
<tbody>
<tr class="context">
<td class="player context">Chloe</td>
</tr>
</tbody>
</table>
The JSON data:
var data = ["Adrian Meador","Bryan Thomas", ... ,"Wendy Leatherbury"];
The Javascript to do this action (here with jQuery):
var directive = {
'tbody tr td[onclick]':
function(arg){
return 'lineClick(\''+arg.item+'\');'
},
'tbody tr td[onmouseover]': '"swapStyle(this, true);"',
'tbody tr td[onmouseout]' : '"swapStyle(this, false);"',
'tbody tr td[style]':"'cursor:pointer'",
'tbody tr[class]':
'tbody tr[class]': function(arg){
//available properties: arg.context, arg.items, arg.pos, arg.item
var oddEven = (arg.pos % 2 == 0) ? 'even' : 'odd';
var firstLast =
(arg.pos == 0) ? 'first' :
(arg.pos == arg.items.length - 1) ? 'last' : '';
return oddEven + ' ' + firstLast;}}
}
$('table.players.2').autoRender(context, directive);
1) An anonymous function
{'tbody tr':
function( argument ){
...
}
}
The argument of this function is an object with the following properties:
- context: the JSON data that is passed to the html template for rendering
- item: the current loop item
- items : the list of all the items of the current loop
When loops are nested, items reference the innermost loop. - pos: the current position in the loop
- If the loop is on an array, pos gives the current index
- If the loop is on a property collection (object), pos gives the name of the current property.
The last 3 properties will be only available inside a loop.
2) A function pointer:
{ 'tbody tr' : rowDecorator }
The same argument will be passed to the function, rowDecorator in our example.
3) A string:
var directive = {'tbody tr td[onmouseover]': '"swapStyle(this, true);"'}
By default a function as a directive is evaluated during the transformation.
If you want to pass a function for instance for an ‘onclick’ event, you just want to pass its name and parameters.
And the function will be evaluated only if the user clicks.
Example
In the example below the ‘anonymous function’ and the ‘string function’ are shown.






