Javascript closures and memory leak risks - javascript

Recetly I was looking for memory leaks in my javascript code. Ater finding some major leaks I starter to look for minor and found something that could be a potential leak - the "hoverIntent.js" plugin. I would like to ask if this is really a leak or am I a bit too overzealous?
General schema fo the code (full code here http://cherne.net/brian/resources/jquery.hoverIntent.js):
(function($) {
$.fn.hoverIntent = function(f,g) {
//...
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
var compare = function(ev,ob) {
//... function body
};
var delay = function(ev,ob) {
//... function body
};
var handleHover = function(e) {
//... function body
};
return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
};
})(jQuery);
I know that many js plugins are written that way, but... If I get that correctly every time I invoke hoverIntent on my object, 3 new functuions (closures) are created? Isn't it a possible memory leak (or at least a performace issue)?
Wouldn't it be better to write is this way:
(function($) {
//create the methods only once on module init?
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
var compare = function(ev,ob) {
//... function body
};
var delay = function(ev,ob) {
//... function body
};
var handleHover = function(e) {
//... function body
};
$.fn.hoverIntent = function(f,g) {
//no closures here
return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
};
})(jQuery);

You are correct, your second example would use less memory because of less closure functions. But as soon as you event isn't callable (element removed etc.) they would disappear again so it is not a "leak" as the memory isn't lost forever.
Also many plugins use the closure by setting the current state of an element in a variable instead of the element itself.

Related

How can I keep same function names meant for different things in their own scope (It may not be the right word)?

I have created two different independent scripts to update two different canvas. The problem is that some of the function names in both the scripts are same. This is going to result in conflicts.
I could combine them together to form a big script but that will soon become messy if I try to add more functionality. Similarly, naming every function differently will be tedious and error prone.
Is there some way, I can keep the scripts with same function names on a single page without any conflict?
Here is my code:
var DropEffect = {
var dropSize, speed;
var createDrops = function () {
var canvas = document.getElementById("drop");
....
};
}
This is the error I get:
Unexpected token name «dropSize», expected punc «:»
Try to do it like this:
File 1:
var nm1 = {
myFunction: function(){
}
}
File 2:
var nm2 = {
myFunction: function(){
}
}
Now, whenever you want to access, use nm1.myFunction() or nm2.myFunction();
In general such kind of objects are called namespaces.
After you modified question,
var DropEffect = {
var dropSize, speed;
var createDrops = function () {
var canvas = document.getElementById("drop");
....
};
}
This is not correct. You are creating variables inside an object (namespace).Objects just understand key-value pairs. Better do it like this,
var DropEffect = {
dropSize : "",
speed : "",
createDrops : function () {
var canvas = document.getElementById("drop");
....
};
}
and now use it as: DropEffect.dropSize etc.
You can wrap code in IIFE's like this:
(function(){
var theFunction = function(){
console.log('foo');
};
theFunction();
}());
(function(){
var theFunction = function(){
console.log('bar');
};
theFunction();
}());

Javascript prototype function override when x

In my case, I'm using the Phaser framework.
So in this example I'm extending the Group class of phaser. Every 'actor' class (Sprite, Group, ...) calls upon the update() prototype every few miliseconds.
My idea was to extend this function only when the application runs on a desktop (so not on a phone).
for example:
var MousePointer = function (game, parent, name) {
Phaser.Group.call(this, game, parent, name);
this.init();
};
MousePointer.prototype = Object.create(Phaser.Group.prototype);
MousePointer.prototype.constructor = MousePointer;
MousePointer.prototype.init = function () {
// ... init
};
MousePointer.prototype.update = function () {
// Do something when on desktop
};
I can't possibly use an if clausule in the update() function to check whether the player is on dekstop/tablet/phone. So is there a way to actually override the prototype on initialisation?
for example (pseudocode):
if(onPhone)
MousePointer.prototype.update = parent.prototype.update;
else
MousePointer.prototype.update = this.update;
Well, you've kind of already written the answer for yourself, haven't you? This code (not inside the init method).
if(onPhone) {
MousePointer.prototype.update = function(){//Phone implementation};
} else {
MousePointer.prototype.update = function(){//Other implementation};
}
I advise against starting off with the "regular" function and then potentially overriding it, since you're just declaring it for nothing.
I think a better way to do this would be to write two different classes that shares the same parent, and then write different update() implementations for them. Then you can just do something like:
if(phone) {
var obj = new PhoneMousePointerObject();
} else {
var obj = new DesktopMousePointerObject();
}
// ... later
obj.update()

Testing multiple browsers with protractor backed by page objects

I'm writing a test where two browsers need to interact. The problem with simply forking the browser is that my page objects still reference the old browser. I didn't want to rewrite all of my PO's to take the browser as a parameter so I tried the first solution found in the link below where they overwrite the global variables with the new browser's version :
Multiple browsers and the Page Object pattern
However, changing the global variables doesn't seem to work as all the subsequent page object functions that I call are performed against the original browser instance. I have tried logging the window handler before and after the switch and they are indeed different which only baffles me further. Here's some of the code.
spec:
var MultiBrowserFunctions = require('../common/multiBrowserFunctions.js');
var HomePage = require('../home/home.po.js');
describe('blah', function(){
it('blah', function(){
MultiBrowserFunctions.openNewBrowser(true);
HomePage.initializePage();
});
});
MultiBrowserFunctions:
(function() {
var browserRegistry = [];
module.exports = {
openNewBrowser: function(isSameUrl){
if(typeof browserRegistry[0] == 'undefined'){
browserRegistry[0] = {
browser: browser,
element: element,
$: $,
$$: $$,
}
}
var tmp = browser.forkNewDriverInstance(isSameUrl);
var id = browserRegistry.length;
browserRegistry[id] = {
browser: tmp,
element: tmp.element,
$: tmp.$,
$$: tmp.$$,
}
switchToBrowserContext(id);
return id;
},
resetBrowserInstance : function(){
browserRegistry.splice(1,browserRegistry.length);
switchToBrowserContext(0);
}
}
function switchToBrowserContext(id){
console.log('---------------------------switching to browser: ' + id);
browser=browserRegistry[id].browser;
element=browserRegistry[id].element;
$=browserRegistry[id].$;
$$=browserRegistry[id].$$;
}
}());
My questions are:
(1) why doesn't this work?
(2) Is there some other solution that doesn't involve rewriting all of my po's?
What you can do is, save the browsers in different variables and then switch between them by overriding the globals via a utility or something.
describe('Switching browsers back and forth', function () {
var browserA, browserB;
it('Browser Switch', function () {
var browsers = {
a : browser,
b : browser.forkNewDriverInstance(true)
};
browserA = browsers.a;
browserB = browsers.b;
var browserAndElement = switchBrowser(browserB);
browser = browserAndElement.browser;
element = browserAndElement.element;
//do your stuff
var browserAndElement = switchBrowser(browserA);
browser = browserAndElement.browser;
element = browserAndElement.element;
//do your stuff
});
});
The switchBrowser() can look like following:
this.switchBrowser = function (currentBrowser) {
browser = currentBrowser;
element = currentBrowser.element;
return {
browser : browser,
element : element
}
}
In this way you don't have to rewrite your POs to take in the new globals.
Hope it helps!
Cheers

What does Jquery.Recup mean?

well i'm confuse about the line witch says "$.Recup ..." I don't know why it is named the same as the plugin name and what it's for.
(function ($) {
$.fn.Recup = function () {
var parametros = {
};
var tsic = true;
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
$.Recup.anterior = function () {
};
$.Recup.siguiente = function () {
}
})(jQuery);
I'm refering to this code, What does $.Recup exactly do?it would be perfect if someone gives me an example please
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
In this case it appears to be a questionable plugin design - especially since $.Recup is not assigned until $.fn.Recup is first called.
However, if it is "appropriately and/or well written" is another question that requires context of (intended) usage. For what it is worth, I would reject this code as written as it smells of misunderstood design and widely scoped side-effects.
Anyway, the way the function is assigned determines how the method can be called.
// let $ be jQuery, then:
$.fn.foo = function () { console.log("foo") }
$.bar = function () { console.log("bar") }
$.foo() // TypeError: $.foo is not a function
$.bar() // -> "bar"
$("sel").foo() // -> "foo"
$("sel").bar() // TypeError: $(..).bar is not a function
That is, $.fn.foo is like .each() - it does something based on the currently selected elements (which are represented by this). On the other hand, $.bar is like jQuery.each() - it provides a way to iterate over a general collection but is not related to a specific set of (previously) selected elements.
In general, a plugin should only add a single entry to $.fn, but directly adding to $ may be useful to expose utility functions - it should definitely be done with care.
Here are two approaches that fix the issue of incorrectly leaked data:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
// Most trivial change; then use recup in this scope
// (or child scopes) only. There is no $.Recup - yay!
var recup = function (opciones) {
};
// ..
}
Or, just expose as local methods:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
function anterior () {
}
function siguiente () {
}
// Just use simple functions in scope
}
This is a jQuery plugin.
jQuery.fn is an alias to jQuery's prototype. So this line lets you call the Recup function on instances of jQuery :
$('#myid').Recup();
Here's the documentation on creating jQuery plugins.

call function inside a nested jquery plugin

There are many topics related to my question and i have been through most of them, but i haven't got it right. The closest post to my question is the following:
How to call functions that are nested inside a JQuery Plugin?
Below is the jquery plugin i am using. On resize, the element sizes are recalculated. I am now trying to call the function resizeBind() from outside of the jquery plugin and it gives me error
I tried the following combinations to call the function
$.fn.splitter().resizeBind()
$.fn.splitter.resizeBind()
Any ideas, where i am getting wrong?
;(function($){
$.fn.splitter = function(args){
//Other functions ......
$(window).bind("resize", function(){
resizeBind();
});
function resizeBind(){
var top = splitter.offset().top;
var wh = $(window).height();
var ww = $(window).width();
var sh = 0; // scrollbar height
if (ww <0 && !jQuery.browser.msie )
sh = 17;
var footer = parseInt($("#footer").css("height")) || 26;
splitter.css("height", wh-top-footer-sh+"px");
$("#tabsRight").css("height", splitter.height()-30+"px");
$(".contentTabs").css("height", splitter.height()-70+"px");
}
return this.each(function() {
});
};
})(jQuery);
I had the same problem. Those answers on related posts didn't work for my case either. I solved it in a round about way using events.
The example below demonstrates calling a function that multiplies three internal data values by a given multiplier, and returns the result. To call the function, you trigger an event. The handler in turn triggers another event that contains the result. You need to set up a listener for the result event.
Here's the plugin - mostly standard jQuery plugin architecture created by an online wizard:
(function($){
$.foo = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("foo", base);
base.init = function(){
base.options = $.extend({},$.foo.defaultOptions, options);
// create private data and copy in the options hash
base.private_obj = {};
base.private_obj.value1 = (base.options.opt1);
base.private_obj.value2 = (base.options.opt2);
base.private_obj.value3 = (base.options.opt3);
// make a little element to dump the results into
var ui_element = $('<p>').attr("id","my_paragraph").html(base.private_obj.value1 +" "+ base.private_obj.value2+" " +base.private_obj.value3);
base.$el.append(ui_element);
// this is the handler for the 'get_multiplied_data_please' event.
base.$el.bind('get_multiplied_data_please', function(e,mult) {
bar = {};
bar.v1 = base.private_obj.value1 *mult;
bar.v2 = base.private_obj.value2 *mult;
bar.v3 = base.private_obj.value3 *mult;
base.$el.trigger("here_is_the_multiplied_data", bar);
});
};
base.init();
}
$.foo.defaultOptions = {
opt1: 150,
opt2: 30,
opt3: 100
};
$.fn.foo = function(options){
return this.each(function(){
(new $.foo(this, options));
});
};
})(jQuery);
So, you can attach the object to an element as usual when the document is ready. And at the same time set up a handler for the result event.
$(document).ready(function(){
$('body').foo();
$('body').live('here_is_the_multiplied_data', function(e, data){
console.log("val1:" +data.v1);
console.log("val2:" +data.v2);
console.log("val3:" +data.v3);
$("#my_paragraph").html(data.v1 +" "+ data.v2+" " +data.v3);
});
})
All that's left is to trigger the event and pass it a multiplier value
You could type this into the console - or trigger it from a button that picks out the multiplier from another UI element
$('body').trigger('get_multiplied_data_please', 7);
Disclaimer ;) - I'm quite new to jQuery - sorry if this is using a hammer to crack a nut.
resizeBind function is defined as private so you cannot access it from outside of it's scope. If you want to use it in other scopes you need to define it like that
$.fn.resizeBind = function() { ... }
Then you would call it like that $(selector').resizeBind()
You have defined the resizeBind function in a scope that is different from the global scope. If you dont'use another javascript framework or anything else that uses the $ function (to prevent conflict) you can delete the
(function($){
...
})(jQuery);
statement and in this way the function will be callable everywhere without errors
I didn't test it:
this.resizeBind = function() { .... }

Categories

Resources