I’m trying to make a simple in in-page popup called like this:
var test = new popObject({}); //JSON options
and I’m having trouble because when I create two in a row, and call show() on the first one, the second one always shows. Both are created, but they aren’t separate somehow, despite being called with new. What am I doing wrong here? I’ve included my code, but I have removed out the irrelevant functions for compactness.
function popObject(options) {
//functions
show = function() {
console.log(boxselector);
jQuery(boxselector).css("display", "block");
return jQuery(boxselector);
}
var hide = function() {...}
var update = function(updateOptions) {...}
var calcTop = function(passedHeight) {...}
var calcLeft = function(passedWidth) {...}
var calcHeight = function(passedHeight) {...}
var stripUnits = function(measure, auto) {...}
var destroy = function() {...}
//public functions
this.show = show;
this.hide = hide;
this.update = update;
this.destroy = destroy;
//constants
name = options.name; //name should never be changed.
boxselector = ".boxcontainer[name=" + options.name + "]";
boxbodyselector = ".boxbody[name=" + options.name + "]";
boxtitleselector = ".boxcontainer[name=" + options.name + "]"
boxboxselector = ".boxbox[name=" + options.name + "]"
title = options.title;
content = options.content;
width = options.width;
height = options.height;
this.name = name;
this.selectors = [boxselector, boxbodyselector, boxtitleselector, boxboxselector]
this.title = title;
this.content = content;
this.width = width;
this.height = height;
//variables
popupHtml = ...
//init code
jQuery("#dropzone").append(popupHtml); this.init = null;
jQuery(".boxbox[name=" + name + "]").css("top", calcTop(width));
jQuery(".boxbox[name=" + name + "]").css("left", calcLeft(height));
jQuery(".boxbody[name=" + name + "]").css("height", calcHeight(height));
}
This is because you’re declaring a lot of variables in the global scope. Try the following code instead:
Note all the
vars that weren’t there before. This defines them as local to the function, and thus local to your object (and also, essentially, private… usethis.instead ofvarto make public members).Anything that isn’t declared with a
varor athis.is considered global. So, when you calledshow(), it used the globalshow, which referenced the object that was created later.