Data-objects Event Cycle

An important concept to understand when developing a web app is the data-object's event cycle. Because of the asynchronous nature of how events are called by data-objects it can be tricky to get right.

As opposed to user events like mouse click and keyboard press which are triggered by user events, data-object events is triggered by the data-object at specific points when something has happened. For instance when a data-object's refreshDataSource() method is called it goes and fetches data from the server. When the data-object has retrieved the data onDataLoaded is triggered. Click the button on the demo below to.

Genres:
$("#dsGenresRefresh").click(function() { dsGenres.refreshDataSource(); }); dsGenres.attachEvent("onDataLoaded", function(){ alert(dsGenres.getDataLength() + " rows loaded from server"); });

Single data-object cycle

List of events

Of the 24 events you can attach to, only a subset of these is needed to know and understand to accomplish most common behaviours. Also, as long as you do not have any master child relations to worry about it all becomes fairly straightforward.

Below a data-object called dsGenres2 have attached every event writing out a log to the console when it is triggered. Open up developer tools and interact with the data-object

Genres2:
// Attach every event to dsGenres2 with a console.log // events is an array with all the events ["onDataLoaded", "onPartialLoaded" etc] events.forEach(function(eventName) { dsGenres2.attachEvent(eventName, function(){ console.log("dsGenres2: " + eventName + " triggered!"); }); }); $(".trigger-events").click(function() { console.log("\n"), count = dsGenres2.getDataLength(), current = dsGenres2.getCurrentIndex(); switch($(this).data("trigger")) { case 'refreshDataSource': dsGenres2.refreshDataSource(); break; case 'setCurrentIndex': dsGenres2.setCurrentIndex((current + 1) % (count )); break; } });

Master child data-object cycle

It all gets somewhat more complicated when having several data-objects with master/child relations.

dsMaster (genres):
dsChild (artists):
// Attach every event to dsGenres2 with a console.log // events is an array with all the events ["onDataLoaded", "onPartialLoaded" etc] events.forEach(function(eventName) { dsMaster.attachEvent(eventName, function(){ console.log("dsMaster: " + eventName + " triggered!"); }); dsChild.attachEvent(eventName, function() { console.log("dsChild: " + eventName + " triggered!"); }); }); $("#script-master .trigger-events").click(function() { console.log("\n"), count = dsMaster.getDataLength(), current = dsMaster.getCurrentIndex(); switch($(this).data("trigger")) { case 'refreshDataSource': dsMaster.refreshDataSource(); break; case 'setCurrentIndex': dsMaster.setCurrentIndex((current + 1) % (count )); break; } });
z