Tag Archives: javascript

Use AOP with RxJS to make functions Observable

There are no Observable create functions that will observe function invocations on an Object. As a proof of concept I used a JavaScript AOP library, Meld, to accomplish this “function to stream” capability.

Alternatives
This sounds like a job for a mixin, proxy, Object.observe, inheritance, or decorator pattern. There are hundreds of mixin libraries, the new JavaScript Proxy is not readily available, Object.observe was cancelled, etc.
Edit: Via a Dan Abramov tweet (what a busy guy!), I found out about MobX.

Aspect-Oriented Programming (AOP)
AOP is paradigm that allows the separation of cross-cutting concerns via applying “advices” to objects. There are many advice types. The Meld library supports several, for example, ‘before’, ‘around’, ‘on’, ‘after’, ‘afterReturning’, and ‘afterThowing’.

We’ll just use two here: “after” to observe a function invocation, and “around” to observe a property change.

Observe of function
In this example object:

var myObject = {
   myProperty:'15',		

   doSideEffect: function(x){this.myProperty = x;},		

   doSomething: function(a, b) {return a + b;}
};

We want to subscribe to the ‘doSomething’ function in this object. That is, when that function is invoked, the resulting return value should be sent to an Observable stream.

The stream:

 
var subject = new Rx.Subject();
    
var subjectAsObservable = subject.map(function(x){
       console.log("in map x:" + x);
       return x;
});
    
var subscription = subjectAsObservable.subscribe(
       function(x){ // onNext
           console.log("Next in subject: " + x.toString());
       }	
);

Now to apply an After advice to that function “joinpoint” we do:

 
var remover = 
  doAfter(myObject, 'doSomething', subject, 
    function(result) {
        console.log("after function .... ");
    }
);

myObject.doSomething(1, 2); 
remover.remove();

The output of running this is:

 
in map x:3
main.js:3
after function .... 

Note that “When adding advice to object methods, meld returns an object with a remove() method that can be used to remove the advice that was just added.”

“doAfter” function is a simple function wrapper of the ‘after‘ Meld function:

 
/**
 * @param anObject the object to advise
 * @param method the method selector
 * @param subject the subject that observes the function
 * @param afterFunction function to invoke after the advised function returns
 * @return object with remove() method
function doAfter(anObject, method, subject, afterFunction){
    return meld.after(anObject, method, function(result){
    	subject.onNext(result);
    	afterFunction(result);
    });
}

Observe of property change
Some AOP libraries support get/set advices on property changes. AspectJ in Java world supports this. Meld does not, but this can be implemented using an Around advice. This type of advice wraps a function call.

With an Around advice we can record a properties’ value before and after a function invocation. If there is a change, we generate a new event for the Observable stream.

 
remover = meld.around(myObject, getMethodNames, function(methodCall){
    var originalValue = myObject.myProperty;
    
    var result = methodCall.proceed();
    if(originalValue != myObject.myProperty){
        subject.onNext("prop changed: " + originalValue + " -> " + myObject.myProperty);
    }
    
    return result;
});

myObject.doSideEffect('25');

remover.remove();

The above uses a utillity function:

/** Utility function to get all functions in object */
function getMethodNames(obj){
   return Object.getOwnPropertyNames(obj)
        .filter(function(name){
	    return typeof obj[name] === 'function';
        });		
}

When any method in object is invoked that changes the property, we get:

in map x:prop changed: 15 -> 25
Next in subject: prop changed: 15 -> 25

Of course, there is a performance cost to this approach of monitoring property changes. This costs has not been quantified or explored.

Summary
Using AOP an object’s functions can be made into observers. An “after” advice can signal a result event, and using an “around” advice, it is possible to generate events on an Object’s properties. Useful? Unknown. Already possible in ReactiveX ecosystem, not sure.

Possible operators for the above could be:
fromFunction(object, methodSelector)
fromProperty(object, propertySelector)
fromProperty(object, methodSelector, propertySelector).

TODO
Look at the Rx.Observable.fromCallback(func, [context], [selector]) operator. Could it be used to go from function to Observable stream without using AOP, as presented here?

Software used
RxJS: version 4.0.7, rx.all.compat.js
Cujojs Meld: version 1.3.1,

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

JSON as a configuration language

JSON as a configuration data file is already a given. I wrote about this before. Google has now made this even more powerful by open sourcing Jsonnet, a “mini-language”, domain specific language (DSL) on this data format. Jsonnet it supports inline comments. Nice!

If your scratching your head and wondering why, JSON is JavaScript, then you don’t understand what JSON is. JSON is a ‘data-interchange format’. It happens to be based on a subset of the JavaScript language, but it could have been in Python, Groovy, or any other scripting language. Undoubtedly, JavaScript’s ubiquitous use on the web is why JSON was optimal.

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Use dojo’s promise.all in non-failure mode

The “all” function “Takes multiple promises and returns a new promise that is fulfilled when all promises have been resolved or one has been rejected.” This makes a lot of sense. If you are invoking multiple asynchronous services in parallel and want to wait for all of them before continuing with a “reactive” function, you probably want to not run this function if one of the services fails.

In some scenarios you do want all the service invocations to complete and then deal with the results whether success or failure. Thus, it would be nice to have a version of ‘all’ that did this.

The now deprecated DeferredList may have supported this. See this reference.

Some() function implementation
Below in listing one I created a function ‘some’ that transforms the input to ‘all’ to accomplish this. This simply takes each promise argument (in array or object) and chains an always(…) Thenable. This Thenable promise link takes a handler that will be invoked whether the prior promise is resolved or rejected. It acts like a ‘finally’ in a try .. catch .. finally.

A better approach would have been to create an alternative to the ‘all’ function that did this.

/**
 * Takes an object or array of promises and creates a new array of 
 * promises that do not fail.
 * <p>
 * The Dojo/All function is fulfilled when all promises 
 * have been resolved or when one has been rejected.
 * In certain scenarios even if some promies
 * @author J. Betancourt 
 * @since 2014/11/04
 * @param objectOrArray  Object|Array?
 * @returns {Array} of promises.
 */
;function some(objectOrArray) {
    "use strict";
    
    var promises = [];
    require([ "dojo/_base/array", "dojo/Deferred", 'dojo/when' ],
      function(array, Deferred, when) {
        var origPromises = [];
        if (objectOrArray instanceof Array) {
            origPromises = objectOrArray;
        } else {
            for ( var key in objectOrArray) {
                if (Object.hasOwnProperty.call(objectOrArray, key)) {
                    origPromises.push(objectOrArray[key]);
                }
            }
        }
        // create array with each item a promise chain.
        array.forEach(origPromises, function(item){
           promises.push(when(item).always(function(res){return res;}));
        });
    });
    
    return promises;  // array of dojo/promise/Promise
    
} // end some(objectOrArray) function

Listing 1

Example
Below in Listing 2, this function is used. Available on jsFiddler.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"  
    data-dojo-config="async:false"></script>
<script src="scripts/some.js"></script>

<script>
    require([ "dojo/Deferred", "dojo/promise/all",
	 "dojo/dom", "dojo/on","dojo/domReady!" ], 
        function(Deferred, all, dom, on) {
        "use strict";    
        
        function show(msg){
            dom.byId('output').innerHTML += msg + '<br/>';
        }
        
        /**
         * Use setTimeout to simulate an async process.
         * @param {string} name the name of this async invoke
         * @param {boolean} fail if true fail the promise
         * @returns {Promise} dojo/promies/Promise
         */
        function async(name, fail){
            var deferred = new Deferred();
            setTimeout(function(){
                if(fail){
                    deferred.reject(name + "Failed!");
                }else{
                    deferred.resolve(name);
                }
            },1000);
            
            return deferred.promise;
        }
        
        /**
         * On click of 'StartButton' button 
		 * wait for an array of promises. 
         */
        on(dom.byId("startButton"), "click", function() {
            var multiples = [async('V0'),
			 async('V1',true),async('V2')];
			 
            var p = all(some(multiples))
            .then(function(result){
                show(result);
                console.log(result);
            },
            function(err){
                // this should not be reached.
                show(err);
                console.log(err);
            });
        });
    });
</script>
</head>
<body>
    <button type="button" id="startButton">Start</button><p/>
    <div id="output" style="border: 1px black solid;width:20em;margin-bottom:20px;">Ready<br/></div>
</body>
</html>

Listing 2

Further reading

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

JavaScript Chaining Promises to Promises

When you create a Promise you can chain asynchronous behavior by using the then(success,fail) method. The success and fail are callback functions invoked appropriately when the promise is resolved or rejected. Note that since ‘then(…)’ returns a promise, this technique is called promise chaining: p.then(…).then(….).

What I discuss in this post are two subjects
1. How to ‘stitch’ multiple promises together?
2. How to ‘splice’ in a value into a promise chain?
3. How to chain using a promise object as an argument?

What if in complex application you already have promises objects and want to create promise chains linking them to each other? How would you do this with ‘then’ methods? Amazingly, in most examples of using Promises on the web this simple scenario is never presented directly. Granted it doesn’t *seem* to be relevant.

Here is the source of a simple demo based on one of the Dojo Deferred examples. It is ‘normal’ promise chaining. I’m using this as the basis for the investigation presented here. The output displayed on page should be: completed with value: 75

The actual chaining ‘stitching’ is setupTrans().then(function(x){return action()}).then(outputValue);

<!DOCTYPE html>
<html >
<head>

<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"  data-dojo-config="async:false"></script>
	
<script>
require(["dojo/when", "dojo/Deferred", "dojo/dom", "dojo/on", "dojo/domReady!"],function(when, Deferred, dom, on){
	  var balance = 100;

	  function asyncProcess(x){
	    var deferred = new Deferred();
	
	    setTimeout(function(){
	      if(x === 'plus' || x === 'minus'){
	      	 x === 'plus' ? (balance += 25) : (balance -= 25);
	      } 
	      deferred.resolve(balance);
	    }, 1000);
	
	    return deferred.promise;
	  }

	  function setupTrans(){
	  	return asyncProcess('z');
	  }

	  function debitAccount(){
		return asyncProcess('minus');
	  }
	
	  function creditAccount(){
		return asyncProcess('plus');
	  }

	  function outputValue(value){
	    dom.byId("output").innerHTML += "<br/>completed with value: " + value;
	  }
	  
	  on(dom.byId("startButton"), "click", function(){
	  	var debit = true;
	  	var action = debit ? debitAccount : creditAccount;
	  	
	  	setupTrans()
	  	.then(function(x){return action()})
	  	.then(outputValue);
	  	
	  });
});
</script>
</head>
<body class="claro">
    <h1>Output:</h1>
	<div id="output"></div><p />
	<button type="button" id="startButton">Start</button>
</body>
</html>

What is ugly is the inline function. Luckily I found the “Flattening Promise Chains” article where the author shows how to get rid of the function and simplify. However that article didn’t answer my question, how can you simply and directly chain promise objects. What the article showed is that you have to use the correct structure or design. Well, of course, but …


Answer
I thought this would be difficult. The Dojo documentation page never mentions that instead of the first ‘then’ argument being onFulfilled handler function it could be an actual promise object. But this is mentioned in specs such as the Promises/A+ specification. Or does it? The ‘Promise resolution procedure’ seems to mix compile time view with runtime, or I’m reading it incorrectly. Q documentation is very good on this. Will have to research further.

To directly chain separate promise chains the above code sample is modified as follows by just using an existing promise as the argument to another chains then(…) method. However, this can only be done using a promise returning function.

  on(dom.byId("startButton"), "click", function(){
  	var debit = true;
  	var action = debit ? debitAccount : creditAccount;
  	
  	setupTrans()
  	.then(action)
  	.then(outputValue);
  	
  });

Or, to inline the decision:

  on(dom.byId("startButton"), "click", function(){
  	var debit = true;
  	
  	setupTrans()
  	.then(debit ? debitAccount : creditAccount)
  	.then(outputValue);
  	
  });


Chaining using actual promise objects inside the then(f,r) is made easy using the approach shown next, using “scalars”.

Chaining values into promise chains
While looking at this subject I thought about a situation where we want to directly insert a known value into the chain so that the next ‘link’ will use this as the prior handler’s return value.

We have a chain, and I want to put the great Answer in there. This won’t work: var p1 = promiseReturningFunction().then(…).then(’42’).then(….).

Sure you can wrap ’42’ in an inline function then(function(){return ’42’}), but that is yucky. How about a function that does that:

     /** return a function that returns the value */
     function now(value){
    	  return function(){return value;};
      }

Now you can do: var p1 = async().then(…).then(now(’42’)).then(….);

Here is the prior source code with the changes. This is just some of the script changes. The output on screen is:

completed with value: 75
completed with value: Goodbye

      /* ...  */

      function outputValue(value){
        dom.byId("output").innerHTML += "<br/>completed with value: " + value;
      }
      
      function now(valueOrPromise){
    	  return function(){return when(value);};
      }
      
      on(dom.byId("startButton"), "click", function(){
        var debit = true;
        var action = debit ? debitAccount : creditAccount;
        
        var promise1 = setupTrans()
        .then(debit ? debitAccount : creditAccount)
        .then(outputValue)
        .then(function(){
        	console.log("now do another promise chain...");
        });
        
        promise1.then((now('Goodbye'))).then(outputValue);
        
      });


Using promise object directly in then(f,r) by using now(x)
With the Promises implementation in Dojo, you can’t use promiseObject.then(anotherPromiseObject). And you can’t use promiseObject.then(when(anotherPromiseObject)). At least, I haven’t figured how to do it.

With the now(x) function shown above, this is easy. The code below will output:

completed with value: 75
completed with value: 100
completed with value: undefined
completed with value: finished both chains

     /** return function that returns the value 
         or apply Dojo's when(...) to return a Promise 
      */
     function now(valueOrPromise){
    	  return function(){return when(value);};
      }
      
      on(dom.byId("startButton"), "click", function(){
        var debit = true;
        var action = debit ? debitAccount : creditAccount;
        
        var promise1 = setupTrans()
        .then(action)
        .then(outputValue)
        .then(function(){
        	console.log("now do another promise chain...");
        });
        
        debit = false;
        action = debit ? debitAccount : creditAccount;
        var promise2 = setupTrans()
        .then(action)
        .then(outputValue);
        
        promise1
        .then(now(promise2)).then(outputValue)
        .then(now("finished both chains"))
        .then(outputValue);
        
      });
});

Groovy language has Promises too
GPars brings Promises to the Groovy language.

Further reading

  1. Flattening Promise Chains
  2. A Deeper Dive Into JavaScript Promises
  3. How-to Compose Node.js Promises with Q
  4. Promise Anti-patterns
  5. dojo/when
  6. q
  7. General Promise Resources
  8. Promises/A+
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Force failure of JavaScript promise in Dojo

For development and unit testing you may need to force a promise chain to fail in various ways.

In listing 1 below is shown a simple XHR request. Now to make sure our promise chain error handling is working correctly we want the Ajax call to fail.

One way of achieving this to just change the url of the XHR destination. This is fine here, but is not a generic approach since not every async function or service is based on a URL or even single value.

Another approach is shown in listing 2. Here we cancel the promise. In Dojo’s promise implementation we can cancel(reason,flag) a promise giving a reason and a flag, and even invoke a cancel handler if the promise was created with one. If this flag is true, a successful async call will result in a failure. Unfortunately, unless you type at superhuman speeds, this can’t be added at a debugger breakpoint and must be coded in temporarily.

Listing 1

/**
 * XHR call.
 * @returns promise
 */
function _loadData(requestParams) {
    var promise;
    require([ "dojo/request"], function(request) {
        promise = request.post("someurl", {
            data : requestParams,
            handleAs : "json",
            preventCache : true
        })
    });
    
    return promise;
}

Listing 2

function _loadData(requestParams) {
    var promise;
    require([ "dojo/request"], function(request) {
        promise = request.post("someurl", {
            data : requestParams,
            handleAs : "json",
            preventCache : true
        })
    });
    
    promise.cancel("force error",true);
    return promise;
}    

There are XUnit type testing frameworks for JavaScript that may be able to do this failure testing better. I have not looked into this yet.

Further reading

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

JavaScript Promise example, reverse geocode location

In prior post we wrapped the Google Map API in a Promise. Now we wrap navigator.geolocation.getCurrentPosition in a similar promise. This allows us to to neatly chain these two to get the browser’s current address.

The example is using Dojo’s Promise implementation, but the approach is applicable to other Javascript Promise libraries or native support.

In listing 1 below I reproduce the former getGeocode function.

Listing 1, Get geocode using Google service

function geoCode(request) {
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();        
        new google.maps.Geocoder().geocode(request, 
          function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                deferred.resolve(results);
            } else {
                deferred.reject(status);
            }
        });
        
    });
    
    return deferred.promise;
    
}

In listing 2 below we have a similar function

Listing 2, get browser location.

function getLocation(){
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();
        navigator.geolocation.getCurrentPosition(
            function navSuccess(position){
                deferred.resolve(position);
            },function navFail(){
                deferred.reject(posError);
            }
        );
    });

    return deferred.promise;
}

Hmmm. The code is very similar. It seems that these two functions could be done using a Promise wrapper function, like toPromise(doFunction, onSuccess, onFailure). Is there such a beast?

Now we can use them together, as shown in listing 3. Here instead of a simple promise chaining we use the technique presented in “Break promise chain and call a function based on the step in the chain where it is broken (rejected)” to “catch” the correct error and not have it bubble up the ‘then’ chain.

Listing 3, get browser location, then reverse geocode

function findCurrentLocation(){
    var request;

    if (navigator.geolocation) {
        getNavLocation().then(
            function navSuccess(position){
                request = {
                    'location' : 
                      new google.maps.LatLng(
                        position.coords.latitude, 
                        position.coords.longitude)
                };

                return getGeoCode(request).
                   otherwise(function geoCodeError(status){
                     throw new Error(status);
                   }
                );
            }, function navFailed(err){
                console.log('navLocation() failed: " + err); 
                throw new Error(err);       
            })
            .then(function geoCodeSuccess(results){
                    console.log('navLocation() success: " + results);
                } 
            );
    }
}

Above, .otherwise(onFailure) is just a shortcut for .then(null, onFailure)

Of course, the code doesn’t have enough error handling and actual use of the data obtained.

Further reading

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Wrap Google map geocoder.geocode in a Promise

Futures and promises are a programming construct to make asynchronous programming easier to apply. They are provided in many JavaScript libraries and frameworks. Below we use Dojo’s implementation to wrap a non-promised based async operation, getting a Geocode from the Google Map API.

The Google geocode service takes a request object (which contains address information) and a callback function that takes a results object and a status string. If status is ok, the results object contains the geocode information (and a lot of other useful information).

In listing one the geoCode function wraps this in a Promise. Inside the function we create a deferred object, then invoke the above async geocode service, then we return the Promise interface of the Deferred object. Note, this is taken from a working application code, and that code works, this below, not tested.

Listing 1.

var geocoder = new google.maps.Geocoder();
 
function geoCode(request) {
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();        
        geocoder.geocode(request, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                deferred.resolve(results);
            } else {
                deferred.reject(status);
            }
        });
        
    });
    
    return deferred.promise;
    
}

You can use this as follows:

var promise = getGeocode(request);

Note that we don’t wait for the async operation to complete, or more correctly, invoke our callback function. The invoker of our geoCode function just gets a Promise object. So?

The Promise object is something that may get a value when it is fulfilled or it may get rejected. You find this out by reacting to those states. How? By using callbacks. So we are right back to where we started, after all the original geocode function also used callbacks. Ah, but here is the difference. With Promises, you are using something with more features and power. The Promise framework allows you to work with async code in a more frameworky way.

One of the nice features of Promises is that they can be “then’able”. “then” functions return a Promise, so they can be chained together: p.then(….).then(….).then(…..); Within each ‘then’, you supply a left and a right callback function, the left is for the resolved, the right is for the rejected state. Example:

var p = getGeocode(request)
p.then(successFunction,failureFunction);

You could also inline everything:

getGeocode(request).then(
    function(results){
       var x = do_something_with_result(results);
       return x;
    },
    function(status){
       do_something_with_status(results);
       throw "failed"
    }
});

These left and right are not chains themselves, there is one chain, but the left or right could be invoked depending on whether the preceding “then” resolved or rejected the promise. Of course, there are more details and each Promise implementation adds their own terminology and features. For example, Dojo has an always function that accepts a callback to invoke no matter what the previous ‘then’ did with the promise.

Apparently moves are afoot to make ‘futures’ part of the core JavaScript standard. These may be following the Promises/A+ specification.

A future blog post will provide a very easy to understand intro to Promises. There doesn’t seem to be a Promise for dummies on the web.

Further reading

YouTube

JavaScript Promises: Thinking Sync in an Async World

Redemption from Callback Hell

Times Developer Network – Promises, Promises

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Template Method Pattern using JavaScript callbacks

JavaScript callbacks are usually discussed in terms of asynchronous behavior. Primary examples given of this are event handlers in the browser or XHR. Callbacks are used so much in JavaScript that there is even a new evil in the world, Callback Hell.

Callbacks are very useful for more familiar coding tasks and it doesn’t have to be about asynchronous services, or journeys into the compsci land of Functional Programming, or Monad this or that.

Template Method Pattern
The term ‘template’ is not related to templates as used in text substitution libraries. This pattern is used when an algorithm or operation has common behavior and the uncommon behavior can be ‘substituted” or deferred by various means.

Though this pattern is usually presented in terms of Inheritance in Class-based Object Oriented Programming, that is just an implementation example. JavaScript can and does implement this pattern; it is just not called by that name.

Simple example
Lets give a very very simple example of what this means. Lets say you have some widget on a web page that presents to the user some recipe based on some input conditions or properties. For simplicity, lets assume that this can be done in one function that consists of a series of statements that are the same except for a few steps.

The usual way to do this is to create multiple functions that change the widget in the required manner, or create one function that uses conditional statements to invoke the correct steps that vary for each type of recipe.

Below in listing 1, we have the behavior for the widget. Some statements come before and after the call of the doSomething() function. The problem with this code is that if we have to do different things, we must complicate the conditional or create other widgetRecipe type of functions that perform the recipe differently.

Listing 1, psuedo code of conditional use
functions widgetRecipe(){
statements before
if(something){
doSomething()
}
statements after
}

Example with callbacks
Since we have a process that differs in only one or more “steps”, the Template Method Pattern is applicable.

The recipe function in listing 1, can be simplified by replacing the conditional statement with the actual function to invoke. Functions in JavaScript are objects, so can be assigned to a variable.

In listing 2, we use the argument name secretSauce for that function that will be passed in. Some tutorials out on the web use the name ‘callBack’ to make it obvious that this is a callback function. Note how the passed in function is invoked, using “()”.

Listing 2, psuedo code using callback
functions widgetRecipe(secretSauce){
statements before
secretSauce();
statements after
}

We can define that function as: var bitterSauce = function(){ alert(“Add a dash of pepper”);}
Then invoke widgetRecipe like: widgetRecipe(bitterSauce);

One famous programmer, Chuck Moore, inventor of the FORTH language, said: don’t decide, compute. Here the function is computed elsewhere, perhaps a table of some kind.

Of course, you can have multiple callback arguments to a function, even an array of callback functions. You can even inline callback functions or make them anonymous. And, a callback function could have arguments too.

Complexities
Used in certain ways, a Callback function is a Closure. This can have, if not used correctly, very subtle issues. In addition, if the callback function uses this internally, you have to invoke it a certain way.

Some of the links below give more information on how to use callbacks and things to watch for.

Real world use?
I am almost done solving a programming problem where I have a ‘Callback Hell’ situation, and to make matters worse, the various slices of this hell needed to be reused. I think I solved it by abstracting out the variable behavior into a callback. Lets see if it survives code review.

Alternatives?
Since JavaScript is Object Oriented, but not via Classes as in Java, it can do inheritance, via prototypes. Thus, the Template Method Pattern can be implemented using prototypical inheritance. This approach is present here, JavaScript Template Method.

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

dojo on.emit won’t work in FireFox?

Seems simple enough, using the Dojo toolkit click a div and trigger an anchor tag on the page.

The code in listing 1 below works on:
Chrome version 35
Internet Explorer 11

Won’t work on FireFox ver 30.

Dojo’s dojo/on module has the emit() method that provides a normalized way to dispatch events. It is supposed to be cross-browser.

From the info on this page, Disabling native events when using Firefox with WebDriver, it sounds like Dojo may, like WebDriver, be using FireFox’s native event facilities and failing.

<!DOCTYPE html>
<html >
<head>
    <script>dojoConfig = {async: true, parseOnLoad: false}</script>
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"></script>
    
    <style media="screen" type="text/css">
        .bold {font-weight: bold;}
        .box {border:1px black solid;margin-top:4em;margin-left:8em;}       
    </style> 
    
    <script>
        require(['dojo/ready','dojo/on','dojo/dom',
                   'dojo/query','dojo/domReady'],
        function(ready,on,dom,query){
            ready(function(){
                var nde = query('#div123');
                nde.on("click",function(evt){
                    on.emit(dom.byId('target'),"click",
                     {bubbles:false,cancelable:false});
                });                 
            });
        });             
    </script>       
    
</head>
<body class="claro">
    <div id="div123" class="bold box">click me!</div>
    <div class="box">
     <a id="target" href="javascript:alert('hello')">will trigger this link</a>
    </div>
</body>
</html>

Listing 1

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Diagnostic Differential Logging with JavaScript Example

Synopsis
Reducing the quantity of information to what is essential is very important in maintaining complex software. Modern development environments have debuggers and other tools to assist in this effort: conditional breakpoints, watch expressions, logging, stop on change techniques, and so forth.
As a supplementary technique an approach to debugging is shown which uses the dynamic differences in a running system to output a reduced level of information. A simple programmatic implementation is shown in a JavaScript scenario, but the technique is applicable using other languages and automated techniques.

KEYWORDS: logging, diff, debugging, diagnostics, BIST, JavaScript, AOP, BIST

Context
Recently I was debugging a legacy JavaScript program. I used the outstanding FireBug plug-in in the FireFox browser. By the way, FireBug is truly indispensible, such a wealth of features and it is FOSS. Now combine that with Selenium which gives you the ability automate the browser and you have a powerful Integrated Development Environment (IDE). All that could be lacking is time and skill.
Unfortunately, I was not finding the problem. Later at home I got an idea. What if I could simply log what changed? That way I could more clearly see how the program behaves. All programs are just obfuscated state machines. Through a use-case or scenario, state variables are being manipulated and non-state data is being changed. Correlating these two with the events that drive the system, is a prime aspect of debugging.

Forces
• You want to log what is happening in a system, but you don’t want to be inundated with non-useful data.
• You or someone else want to be able to quickly resume this investigation in another situation or project.
• By saving ‘interests’, a Built-in-self-test aid can be implemented.
• During development hooks can be put in place to provide differential logging.
• You want to capture the live system not a system which is controlled by a debugger.
• You cannot install new systems, tools, or frameworks to help.
• Breakpoints will break as the system is maintained.

Solution
My solution was to dynamically log the differences. I’m sure this is not new. However, it probably is not explicitly discussed. The usual approach is to log as much as possible, but since this is prohibitive, instead the logging is limited, level filters, and contexts are used to control the output. Breakpoints and watches while usually enough to do the job are in the long term brittle since the target program may change during the dev and debug process. Thus, dynamic difference reporting would be a better approach in this situation.

Consequences
Todo.

Implementation
There are a few implementation choices.

API
One is to declare the data of interest. Then the logging system will track these and only output anything when there is a change in any of the data. With this approach the logger must be triggered either manually or automated. Manually is very easy; at an event change or at enter and exit points of a module or function, the differential logger is invoked.

Automated
To avoid changing the source code (it may not even be available), AOP could be used to implement the above. For example, an Around advise can be used to differentially trace the changes in methods.

Framework Plugin
If the system under test is running as part of a debug or is instrumented, it may already have a facility to capture change events. For example, FireBug, the FireFox plugin has this and the FireBug plug-in, FireDiff, implements a change monitor and visualization output. There may be or should be a comparable plug-in for other systems like the Eclipse IDE.

Code Example
To illustrate this concept it is used to debug a web page’s DOM changes via JavaScript. The page has a button that when clicked will randomly change two input field’s content. Notice that when the change involves just an ordering of two adjacent characters in a field, it is not readily apparent. The Differential logging makes it explicit. The log output is just the result object converted to JSON. An example: {“event”:”run”,”record”:{“foo2”:[“”,”accd”],”foo4″:[“”,”ollrr”]}}. A real implementation would do otherwise.

To specify which DOM nodes to monitor, a JavaScript object is used:

{"foo2":{"get":"v"},"foo4":{"get":"v"}};

The “get” field is used to specify how to get the value from the browser DOM. Another method would be “innerHTML” access. A better approach is to detect the appropriate ‘getter’ via using the node type.

demo screen capture

Listing 1, implementation


/**
 * 
 * Differ constructor.
 * 
 * @param data which nodes to record
 * @param formatter how to show results
 * @returns
 */
function Differ(data, formatter){
	this.data = data;
	this.formatter = formatter;
	
	if(!formatter){
		this.formatter =this.format;
	}
};

/**
 * Data and methods of class.
 * 
 */
Differ.prototype = {
  MAXSIZE : 15,
	
  /**
   * Detect changes and save latest.
   * 
   * @param event Where was diff created
   * @returns result object
   */
  diff : function(event){
    var results = {};
		
    if(!data){
    	return results;
    }
		
    if(event){
    	results = {"event":event};
    }
		
    results["record"] = {};
		
    var record = results["record"];
		
    for(var key in data){			
      var ref = document.getElementById(key);			
      var domValue = "";			
			
      switch (data[key].get) {
        case "v":
          domValue = ref ? this.shorten(ref.value) : "";
          break;
        }
			
        var prior = data[key].value ? data[key].value : "";
			
        if((domValue != prior)){
          record[key] = [prior, domValue];
          data[key].value = domValue;
        }
    } // end for	
		
    return results;
		
  }, 

  /**
   * Convert results to message.
   * 
   * @param results object
   * @returns JSON
   */
  toMessage : function(results){
    var obj = results;
    if(!results){
      obj ={"error":"results is undefined or null"};
    }		
		
    return this.format(JSON.stringify(obj));
  },
	
  /**
   * Get size of an object
   * @param obj
   * @returns {Number}
   */
  size : function(obj){
    var len = 0;
    for(var key in obj){
      if(obj.hasOwnProperty(key)){
        len++;
      }
    }
		
    return len;
  },
	
  /**
   * Limit size of value.
   * 
   * @param value
   * @returns
   */
  shorten : function(value){
    return (value.length > this.MAXSIZE) ? 
	value.substring(0,this.MAXSIZE-1):value;		
  },
	
  /**
   * Make message human readable.
   * 
   * @param message
   */
  format : function(str){
  	return str + '<br/>';
  }	
	
};	

Listing 2, Demo script

var data = {
  "foo2" : {
    "get" : "v"
   },
  "foo4" : {
    "get" : "v"
   }
};

var differ = new Differ(data);
differ.diff(); // prime values

function runIt() {
  var ref2 = document.getElementById('foo2');
  var ref4 = document.getElementById('foo4');
	
  if(Math.floor(Math.random()*101) > 60){
    swapInputs(ref2,ref4);
  }else{
    scramble(ref2,ref4);
  }

  var msg = differ.toMessage(differ.diff("run"));
  document.getElementById('output').innerHTML += msg;
  document.getElementById('output').innerHTML += 
    Array(60).join("-") + "<br/>";
}

function scramble(ref2, ref4){
  var ch = ref2.value.charAt(1);
  var r2v = ref2.value;
  ref2.value = replaceChar(r2v, 2, ch);
  ref4.value = replaceChar(ref4.value, 2, ref4.value.
    charAt(1));
}

function swapInputs(ref2,ref4){
  var temp = ref2.value;
  ref2.value = ref4.value;
  ref4.value = temp;	
}

function replaceChar(str, ndx, v) {
  return str.substr(0, ndx) + v + 
    str.substr(ndx + v.length);
}

Listing 3, the demo web page

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; 
    charset=iso-8859-1">
  <link rel="stylesheet" type="text/css" href="style.css" />	
  <script type="text/javascript" src="DebugUtils.js"></script>	
  <script type="text/javascript" src="DemoDiff.js"></script>	
</head>
<body>
  <span class="mytitle">Differential Logging Example</span>
  <div style="width:600px;">
	<div class="box inputBox">		
		1: <input type="text" id="foo1" value="xyyz"/>
		2: <input type="text" id="foo2" value="acbd"/><br/>
		3: <input type="text" id="foo3" value="wzlm"/>
		4: <input type="text" id="foo4" value="olxrr"/>

          <span class="buttonClass">
	    <input type="button" id="run" value="Test" 
               onclick="runIt()"/>
	  </span>		
	</div>
	Output
	<div id="output" class="box inputBox"></div>
	<span style="float:right;margin-right:10em;font-size:xx-small;">
           &copy; Josef Betancourt</span>		
	</div>
</body>
</html>

Listing 3, css

body {
  background-color:#E6E6E6;margin:3em 8em 12em 3em;
}	
.box{
  border: 3px solid #D4D4D4;padding:8px;
  padding:2em 1em 2em;margin:10px 5px 20px;
}
.inputBox{
   background-color:Beige;margin-right:36px;
   width:475px;font-family:monospace;
}
.buttonClass{
    float:right;margin-left:1em;margin-right:3em;
}
.mytitle{
   text-decoration:underline;font-weight:bold;
}

Related Patterns
None.

Related Intellectual Property
None.

Further Reading

Debuggers are for Losers

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.