Use callback functions
Documentation updated on December 13rd.
Contents
Overview
In this tutorial, we'll learn how to use callbacks to know when a component change into a different state.
Defining callback functions
Almost every component has different states, you can know when something happens through callback functions.
To assign a callback function simply use the on method exposed by all UI components.
The on method receipt 2 arguments:
- Callback name
- Handler to be executed
Let's see an example with Modal component:
var myModal = $("#my-modal").modal("Some content.");
myModal.on("show", function () {
// Inside the callback function
});All the available callbacks are written down for each component on theAPI Documentation.
The scope inside
To make things easy, each callback has a special scope inside its function context.
Through the this keyword you can access to the component instance to keep on working with it.
Let's see an example:
var myModal = $("#my-modal").modal("Some content.");
myModal.on("show", function () {
this.content("New content for 'this', the Modal.").widht(500).heigth(300);
});Complex behaviors
You can easily create more complex behaviors by combining a few components through callback functions.
For example: First create an empty Modal.
var myModal = $("#my-modal").modal();Then, create a Form controller...
var myForm = $("#my-form").form();...and define a "submit" callback:
myForm.on("submit", function () {
// Change Modal content and show it
myModal.content("<p>Are you sure?</p>").show();
});Deferred callbacks
Another useful pattern is to assign deferred handlers to callbacks. That way you could assign behavior to the components depending on user behavior or your app configuration. To accomplish that all Objects have the public method on, that let you define deferred callbacks, and other method called off, to remove callbacks.
For example, creating a Modal with some content...
var myModal = $("#my-modal").modal("/some/content.html");...you can do something different for logged users:
if (user.isLogged) {
myModal.on("show", function(){
// Do something
});
} As you see in the previous example, the use of the on method to assign special behavior to logged users with a cool and simple sugar syntax.