var newMap = function(obj, fn) {
var options = $.extend( {}, obj);
for (key in options) {
options[key] = fn(options[key]);
}
return options;
};
$(document).ready(function() {
var obj = {
url: "http://jquery.com/",
success: function() {output.add("Hurrah!");},
failure: function() {output.add("Boohoo!");}
};
var myInstrumentation = function(option) {
if ($.isFunction(option)) {
return function() {
if (!this.count) this.count = 0;
this.count++;
option();
}
} else {
return option;
}
};
var newObj = newMap(obj, myInstrumentation);
newObj.success.call(newObj);
newObj.failure.call(newObj);
newObj.success.call(newObj);
output.add("Total calls: " + newObj.count);
});
In a thread on the jQuery development mailing list gMinuses suggest that the jQuery map
function be extended to work on arbitrary objects. If I'm not mistaken, the suggested code for the non-array branch would be something like this newMap
function.
If so, I see a problem. If the object is just slightly more complicated, I believe, things start to fall apart.