$Y allows you to write concise and readable asynchronous code, providing the following capabilities:
You can use $Y instead of the following "anti-patterns" for asynchronous JavaScript programming: 1. Passing a callback function as a method parameter 2. Using publish-subscribe as an asynchronous callback
The following code provides an example of anti-pattern 1: function loadXmlAsync(url, callback) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (callback) callback(req.responseXML); }; req.open("GET", url, true): req.send(); } loadXmlAsync("data.xml", function(doc) { jsx3.log("Got document: " + doc); }); As shown in the example, passing a callback function works but can get messy and there is no standard idiom. The following questions may arise:
The following code provides an example of anti-pattern 2: this.loadXmlAsync = function(url) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { this.publish({subject:"done", doc: req.responseXML}); }; req.open("GET", url, true): req.send(); }; this.subscribe("done", function(evt) { jsx3.log("Got document: " + evt.doc); }); this.loadXmlAsync("data.xml"); The following issues may arise with anti-pattern 2:
The following example shows how to use $Y to implement the function in the previous examples. this.loadXmlAsync = jsx3.$Y(function(cb) { var url = cb.args()[0]; var req = new XMLHttpRequest(); req.onreadystatechange = function() { cb.done(req.responseXML); }; req.open("GET", url, true): req.send(); }); this.loadXmlAsync("data.xml").when(function(doc) { jsx3.log("Got document: " + doc); }); |
Contents
|
