Skip to content

Latest commit

 

History

History
51 lines (38 loc) · 2.08 KB

04.custom-attribute-directives.md

File metadata and controls

51 lines (38 loc) · 2.08 KB

04. Custom Attribute Directives

As you could've seen in 02. Built-in Attribute Directives, the list of built-in attribute directives is quite limited and it's probable, that you'll require custom ones. Each custom attribute directive is reevaluated on each context.refresh(), please be aware, that in case of assigning events will happen multiple event assignation. Be careful with using this functionality.

How to create directive

Instance of our application provides function called attribute, that expects name and definition function of directive. The definition function accepts parameters element, attributeValue and context.

  • element is DOM element, that uses our custom attribute directive.
  • attributeValue is value, that is accepted from context. It could point to specific value, to static value or else.
  • context is reference to context of space, where is element presented.

Example

Let's assume our index.html file as, where we have our directive called bgcolor:

<html ajsf="app">
	<head>
		<script type="text/javascript" src="js/nunjs.min.js"></script>
		<script type="text/javascript" src="js/ajsf.min.js"></script>
		<script type="text/javascript" src="js/app.js"></script>
	</head>
	<body>
		<div bgcolor="myColor">My content</div>
	</body>
</html>

For this we have to also create application in app.js.

var app = ajsf('app', function(context) {
	context.myColor = '#ff00ff';

	return context;
});

To add attribute, we need to have reference to application. Application itself provides function attribute, that defines our directive.

app.attribute('bgcolor', function(element, attributeValue, context) {
	element.style.background = attributeValue;
});

On each change of 'myColor' our elements accepts value as its background color. If attribute is inside custom element directive or ajsf-repeat, context.refresh() could be required.


Previous chapter: 03. Built-in Filters

Next chapter: 05. Custom Element Directives