All event binding and triggering is done via jQuery events. This prevents accidental triggers if the related dom element is no longer in scope.
Binding an event is very similar to the jquery bind syntax. For example, this causes content to be loaded dynamically via ajax when the page value in the url changes:
$('#pageContent').hr('page',function(value){
$(this).load(value + '.html');
});
You can bind multiple events to the same dom object, and they will be called whenever those values update. You can also bind multiple events to the same function by putting them in an array. The function will only be called once when one or more of the values change.
$('#pageContent').hr(['page', 'productID', 'pics'],
function(values){
var page = values.page;
var productID = values.productID;
var showPictures = values.pics;
}
);
Events are always called in route order which helps prevent unnecessary callbacks during page transitions. Suppose a user at this url:
http://example.com/#!/view/21/show
The user then navigates to the list view page:
http://example.com/#!/list
If we have some code set up to toggle the pictures on and off based on the url, we don't want to hide the picture if the entire page is changing.
//called first
$('#pageContent').hr('page',function(value){
$(this).load(value + '.html');
});
//called second, as it is later in the url
$('#pictureViewer').hr('pics', function(value){
if(value = 'show'){
$(this).show();
} else {
$(this).hide();
}
});
Fortunately jQuery event binding is smart enough not to call this event if the #pictureViewer is no longer in the DOM. We need to do one more thing to make sure that this event is not called. The jQuery load event only replaces the HTML after it is loaded from the server, so we need to empty it out before returning from the page load function.
$('#pageContent').hr('page',function(value){
$(this).html('').load(value + '.html');
});
Rather than being alerted to every value for a variable, specify the exact value or values that must be present for the bind to trigger. For example to only trigger when change is 'red' or 'blue':
$('#element').hr({color:['red', 'blue']}, function(value){
alert(value); //red or blue
});
When specifying valid values you can specify more than one varaiable and the values that are valid for each variable.
$('#element').hr({color:['red', 'blue'],number:[1,2,3]}, function(values){
alert(values.color); //red, blue
alert(values.number); //1,2,3
});
To specify that all values are valid for one variable use an emty array.
$('#element').hr({color:['red', 'blue'],number:[]}, function(values){
alert(values.color); //red, blue
alert(values.number); //any value
});