An Essential application is built with modules called behaviors
Every behavior describes a specific functionality of your application
You can nest behaviors, initialize behaviors inside others, and share logic between them. They are designed to be fast and testable entities.
The box on the rigth is an example of a behavior in action
Page = {};
Page.TabbedContainer = Essential.Behavior.extend({
init: function() {
// Called on initialization
},
events: {
"click .tab-header": "switchTab"
},
switchTab: function(e) {
// this.el => domElement
}
});
Essential.start(Page);
<div behavior="tabbed-container">
<ul>
<li class="tab-header" data-content="js">
</li>
<li class="tab-header" data-content="html">
</li>
</ul>
<div class="tab-content active" data-name="js">
<!-- Tab content here -->
</div>
<div class="tab-content" data-name="html">
<!-- Tab content here -->
</div>
</div>
Once you have defined your behaviors there are two ways to attach a behavior to a DOM element:
- Define a data-behavior attribute for the element with the associated behavior, Essential will automatically start a new behavior with the element accesible through the el property.
- Instantiate a behavior manually with the new method, passing the DOM element to be attached as argument.
You can define behaviors based on other behaviors with the extend method
App.StandardCarousel = Essential.Behavior.extend({
events: {
"click .arrow" : "changeSlide"
}
});
App.CoolCarousel = App.StandardCarousel.extend({
//...
});
<div>
<ul behavior="cool-carousel">
<li><img src="/assets/image1"></li>
<li><img src="/assets/image2"></li>
<li><img src="/assets/image3"></li>
<li><img src="/assets/image4"></li>
<li><img src="/assets/image5"></li>
</ul>
</div>
Due to the module-oriented nature of essential, it's really easy to write tests.
This example uses mocha, but you can use any test framework you like.
describe("CoolCarousel", function() {
beforeEach(function(){
this.domElement = __html__["cool_carousel.html"];
});
it("....", function(){
App.CoolCarousel.new(this.domElement);
});
});
Behaviors can share information and communicate among themselves through the DOM Event interface
App.Editor = Essential.Behavior.extend({
events: {
"keyup": "emitChangedContent"
}
emitChangedContent: function() {
var customEvent = new CustomEvent("editor:changed", {
"detail": {
content: this.el.innerHTML
}
});
document.dispatchEvent(customEvent);
// or this.el.dispatchEvent(customEvent);
}
});