Question

In this jsfiddle, the author writes a test for some custom knockout binding. As part of the test, it seems that he/she extends jQuery.

Is my understanding of line 30. $.fn.on = function(event, callback) { that it overrides, without subsequent cleanup anything that jQuery might have defined as on on its prototype? Same question for line 36 and the fadeOut.

Here's the relevant snippets and you can check the fiddle to look for cleanup:

30. $.fn.on = function(event, callback) {
31.   ...
...
36. $.fn.fadeOut = function(speed, callback) {
37.   ...

I am asking in general, not directly related to jquery (i.e. jquery may or may not have anything for on and fadeOut.) I am considering embedding a similar test into production code and I don't want my test altering jQuery or whatever "real" object my test may be touching that way. On that note, it seems that even if there was cleanup, some other event-driven (async) calls may stumble on the changed implementations - am I right?

Was it helpful?

Solution

It doesn't only override anything defined in the prototype, it actually replaces it. The $.fn property is a copy of the prototype for the jQuery object, so $.fn is the actual prototype, i.e. $.fn === jQuery.prototype.

You are correct that you can't isolate such a change to your own calls to the object, it would also affect any other code calling the object as long as your change was in effect.

However, as jQuery is strictly single threaded, you could change the prototype, use the object and then change the prototype back, and no other code could be affected. As long as you have code running without a break, there are no events handled.

OTHER TIPS

Yes it overrides jQuery's prototype. It doesn't extend anything, $.fn is an alias for jQuery's prototype (line 54 of core.js is jQuery.fn = jQuery.prototype = {...}) so overwriting $.fn.on blows away jQuery.

Watch the log here: http://jsfiddle.net/LzGmJ/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top