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() {
this.helper();
output.add("Hurrah!");
},
failure: function() {
this.helper();
output.add("Boohoo!");
},
helper: function() {
// do something here
}
};
var myInstrumentation = function(option) {
if ($.isFunction(option)) {
return function() {
if (!this.count) this.count = 0;
this.count++;
option.call(this);
}
} 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.
In the simpler case, this works fine. If the object is just slightly more complicated, though, I believe, things start to fall apart, as can be seen here. Although there are only three calls to the known functions, the internal calls to helper()
also increment the counter.
If this is the intended use, I'd suggest an easier approach and not try to extend map.