Using "this" in a constructor - javascript

I am attempting to make a project which does two way data binding on two specified variables. However, when I tried it out, the project did not seem to be working.
I'm pretty sure that what I did wrong is that I specified a constructor, and then inside, I created a variable using "this," a function using "this," and then I tried to use the first variable inside the function using "this." Is this allowed?
The code for my project is in the snippet below.
function glue(varOne, varTwo, interval = 60) {
this.varOne = varOne;
this.varTwo = varTwo;
this.varOneClone = this.varOne;
this.varTwoClone = this.varTwo;
this.interval = interval;
this.onChange = function(changedVar) {
if (changedVar == this.varOne) {
this.varTwo = this.varOne;
} else if (changedVar == this.varTwo) {
this.varOne = this.varTwo;
}
this.varOneClone = this.varOne;
this.varTwoClone = this.varTwo;
};
this.intervalID = setInterval(function() {
if (this.varOne != this.varTwo) {
if (this.varOne != this.varOneClone) {
this.onChange(this.varOne);
} else if (this.varTwo != this.varTwoClone) {
this.onChange(this.varTwo);
}
}
}, this.interval);
this.clearUpdate = function() {
clearInterval(intervalID);
};
this.changeUpdate = function(newInterval) {
this.interval = newInterval;
clearInterval(intervalID);
this.intervalID = setInterval(function() {
if (this.varOne != this.varTwo) {
if (this.varOne != this.varOneClone) {
this.onChange(this.varOne);
} else if (this.varTwo != this.varTwoClone) {
this.onChange(this.varTwo);
}
}
}, this.interval);
};
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Glue</title>
</head>
<body>
<input id="input" type="text"></input>
<p id="output"></p>
<script>
var input = document.getElementById("input");
var output = document.getElementById("ouput");
var glue = new glue(input, output, 60);
</script>
</body>
</html>
Thank you!
Edit:
I've tried using the var self = this; method which two people recommended, but it still refuses to work. The error from the console is TypeError: glue is not a constructor, but I'm not sure why this happens. I want glue to be a constructor. Please help! The new code is below.
function glue(varOne, varTwo, interval = 60) {
var self = this;
self.varOne = varOne;
self.varTwo = varTwo;
self.varOneClone = self.varOne;
self.varTwoClone = self.varTwo;
self.interval = interval;
self.onChange = function(changedVar) {
if (changedVar == self.varOne) {
self.varTwo = self.varOne;
} else if (changedVar == self.varTwo) {
self.varOne = self.varTwo;
}
self.varOneClone = self.varOne;
self.varTwoClone = self.varTwo;
};
self.intervalID = setInterval(function() {
if (self.varOne != self.varTwo) {
if (self.varOne != self.varOneClone) {
self.onChange(self.varOne);
} else if (self.varTwo != self.varTwoClone) {
self.onChange(self.varTwo);
}
}
}, self.interval);
self.clearUpdate = function() {
clearInterval(intervalID);
};
self.changeUpdate = function(newInterval) {
self.interval = newInterval;
clearInterval(intervalID);
self.intervalID = setInterval(function() {
if (self.varOne != self.varTwo) {
if (self.varOne != self.varOneClone) {
self.onChange(self.varOne);
} else if (self.varTwo != self.varTwoClone) {
self.onChange(self.varTwo);
}
}
}, self.interval);
};
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Glue</title>
</head>
<body>
<input id="input" type="text"></input>
<p id="output"></p>
<script>
var input = document.getElementById("input");
var output = document.getElementById("ouput");
var glue = new glue(input, output, 60);
</script>
</body>
</html>
Thanks for your help!

There are few problems that you could fix, as you said, you're using this everywhere. this might not always point to the same object in some context so if you want to use the same object, you could use a variable accessible from the scope.
Usually, people use a variable named self:
var self = this
Then the self variable should be used everywhere where you want to access specifically that object. So in your onChange and setInterval, it would be a better idea to access this by using the self object.
One other way, would be to instead bind a bounded function. In this case, the this object will be the one you bound the function to.
this.onChange = (function () {
// here this will be equal to context
}).bind(context)
In this case, you can set context to this and within the function you can still use this without worrying which object will be this.
You can also make sure to call method using this.func.call(this, params...) or this.func.apply(this, paramArray).
There are a lot of ways to fix this, but if you search about bind, apply and call. It will be enough to understand how to make more complex construction for your code.
To give you an idea of how bind works, take this example:
function bind(method, obj) {
// Create a callable
return function () {
// Pass the arguments to the method but use obj as this instead
return method.apply(obj, arguments);
}
}
function func(a, b, c) {
console.log(this, a, b, c)
}
var bound1 = bind(func, {a: 1})
var bound2 = bind(func, {a: 2})
func(1,2,3)
bound1(3,4,5)
bound2(6,7,8)
You'll see that when func isn't called, this defaults to window. But in case of bound1 and bound2, it will be using the second parameter of bind.
All that to say that you can control which object will be used as this but if you don't specify which object is going to be used, then you might end up using window as this like in a setInterval. In other words, the keyword this isn't scoped like other variables. It depends of the context, not of its place in the code.

The problem is that the setInterval callback is made in a different context, so this will no longer be your glue object. Since you're running within a browser, it will be the window object. I'm pretty sure that all the other times you use this, it is referencing the correct object.
There are a few options to handle this. The first is to use the .bind() method. It is definitely the cleanest, and requires the least amount of "tweaking". However, it's not supported by IE8. Hopefully you don't have to support that browser, considering MS has dropped support for it, except for in embedded systems. Here's how it would work:
this.intervalID = setInterval(function(self) {
if (this.varOne != this.varTwo) {
if (this.varOne != this.varOneClone) {
this.onChange(this.varOne);
} else if (this.varTwo != this.varTwoClone) {
this.onChange(this.varTwo);
}
}
}.bind(this), this.interval);
Another option is to create a variable that holds the value of this before you call setInterval and then rely on the closure to give you access to that variable:
function glue(varOne, varTwo, interval = 60) {
var self = this;
//...
this.intervalID = setInterval(function() {
if (self.varOne != self.varTwo) {
if (self.varOne != self.varOneClone) {
self.onChange(self.varOne);
} else if (self.varTwo != self.varTwoClone) {
self.onChange(self.varTwo);
}
}
}, this.interval);
//...
}
Finally, you could also use an immediately-invoked function to pass in the value of this without creating a closure:
this.intervalID = setInterval((function(self) {
return function() {
if (self.varOne != self.varTwo) {
if (self.varOne != self.varOneClone) {
self.onChange(self.varOne);
} else if (self.varTwo != self.varTwoClone) {
self.onChange(self.varTwo);
}
}
}
})(this), this.interval);
EDIT:
Everything said above is a problem and the options given for solving it should fix that problem. However, it's one of only a few problems in your code sample.
There's also a problem with the line var glue = new glue(input, output, 60);. You can't have a variable with the same name as a function. If the function is declared first, as it should be in this case, then the variable overwrites it, so the function essentially no longer exists by the time you call new glue(). This is why you are getting the glue is not a constructor error.
I see that in your jsbin you've changed the variable name to tape. That fixes the problem. However, jsbin puts all the code from the JavaScript pane at the bottom of your body. You need the function to be declared before the var tape = new glue(input, output, 60); line, since that line is calling the function. You can tell jsbin where to put the code from the JS pane, by putting %code% where you want it in in the HTML pane. So, if you put a line like <script>%code%</script> before your existing script block, it should fix that. This is totally just a quirk of using jsbin, and won't apply to code you have running in a standalone website (although, even on your standalone site, you need to make sure that the code declaring the glue function comes before the code calling it).
Now, that gets rid of all the errors that are being thrown, but still, the code isn't actually DOING anything. This is because near the beginning of the constructor you have:
this.varOneClone = this.varOne;
this.varTwoClone = this.varTwo;
So varOne starts out equal to varOneClone, and varTwo starts out equal to varTwoClone. The only other place you set them is inside the onChange method, but you only call onChange if varOne != varOneClone or varTwo != varTwoClone. It's like you're saying "Make these 2 values the same, then if they're different, call onChange." Obviously, in that case, onChange is never going to be called.
I realize that it's possible you have more code than you've included here, that IS changing those properties, but I think your goal is to check if the text WITHIN varOne or varTwo has changed, and if so, update the other one, rather than checking if the elements themselves have changed. Since the text can be changed by the user (at least for varOne, since that's an input), it can be changed outside of code. If assumption is correct, you need something like this:
function glue(varOne, varTwo, interval = 60) {
this.varOne = varOne;
this.varTwo = varTwo;
this.varOneCurrentText = this.varOne.value;
this.varTwoCurrentText = this.varTwo.textContent;
this.interval = interval;
this.onChange = function(changedVar) {
if (changedVar == this.varOne) {
this.varTwo.textContent = this.varOneCurrentText = this.varTwoCurrentText = this.varOne.value;
} else if (changedVar == this.varTwo) {
this.varOne.value = this.varOneCurrentText = this.varTwoCurrentText = this.varTwo.textContent;
}
};
this.intervalID = setInterval(function() {
if (this.varOne.value != this.varTwo.textContent) {
if (this.varOne.value != this.varOneCurrentText) {
this.onChange(this.varOne);
} else if (this.varTwo.textContent != this.varTwoCurrentText) {
this.onChange(this.varTwo);
}
}
}.bind(this), this.interval);
//...
}
A couple things to note about this. First, notice that I'm using .value for varOne but .textContent for varTwo. This is because you're passing in a form element (an input) for varOne and a non-form element (a paragraph) for varTwo. These types of elements have different ways of getting their current text. If you can design it so that only form elements will ever be passed in, it will make things easier. But if not, since you probably won't know in advance what type of elements are passed in, you'd need to add a check at the beginning, so you can use the correct property.
Also, while this should work, it would really be better to use events rather than having a continuous loop in the setInterval looking to see if the text has changed. The input has a change event that will be fired anytime its value is changed. You could just update varTwo whenever that event is fired. I don't think there's a similar event for the paragraph element, but you could create a custom event for it. I'm assuming that you're planning on having some other code that will update the text inside the paragraph, since that's not something the user can do directly. If so, then you could fire your custom event at the same time that you update its text. Then when that event is fired, you could update varOne.
I just noticed a typo in a line you have, as well:
var output = document.getElementById("ouput");
The element ID should of course be "output".

Related

Can you alter a statement in a javascript function after is run once

I'm having a hard time figuring this out. I'd like the xxp.run.pause(); to be replaced by xxp.run.play(); after the initial code below is actioned by a user once. I've tried creating a closure but I'm not sure I set it up right. Any help would be very much appreciated.
doSkip: function() {
XXP.run.removeListener('canper', XXP.Skip);
XXP.run.currentTime = XXP.skipTo;
XXP.run.pause(); // this is what I would like to change
}
You may set a flag somewhere which records whether or not the doSkip function has been called before:
var hasSkip = false;
doSkip: function() {
XXP.run.removeListener('canper', XXP.Skip);
XXP.run.currentTime = XXP.skipTo;
if (!hasSkip) {
XXP.run.pause();
hasSkip = true;
}
else {
XXP.run.play();
}
}
You can wrap the function in an IIFE with a persistent variable that checks to see if it's been paused. This has the advantage over having a separate variable elsewhere because hasPausedOnce is only needed for the doSkip function - no need to populate the outer scope (which can have readers of your code worrying about whether hasPausedOnce is going to be altered elsewhere)
doSkip: (() => {
let hasPausedOnce = false;
return function() {
XXP.run.removeListener('canper', XXP.Skip);
XXP.run.currentTime = XXP.skipTo;
if (!hasPausedOnce) {
XXP.run.pause();
hasPausedOnce = true;
} else XXP.run.play();
};
})()

probably moronic js syntax error. Object is null

var fbToggle = document.getElementById("fbToggle");
and later in the script
fbToggle.addEventListener("click", toggle("fbContainer"));
Console tells me that fbToggle is NULL
This is in the document though.
<input type="checkbox" id="fbToggle">
I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?
EDIT :
entire js :
function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}
function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}
window.onload = init();
HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.
It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.
window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
http://jsfiddle.net/ST938/
Another point is addEventListener expects a function or function idenitifier, NOT a function call.
addEventListener("click", toggle("fbContainer")); // wrong
addEventListener("click", toggle); // correct
So if you want to pass a parameter
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:
window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload
The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:
fbToggle.addEventListener("click", function() { toggle("fbContainer"); });
or you can use bind:
fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));

need help understanding closures usage in this code

Here is a simplified snippet from some code I wrote for managing tablet gestures on canvas elements
first a function that accepts an element and a dictionary of callbacks and register the events plus adding other features like 'hold' gestures:
function registerStageGestures(stage, callbacks, recieverArg) {
stage.inhold = false;
stage.timer = null;
var touchduration = 1000;
var reciever = recieverArg || window;
stage.onLongTouch = function(e) {
if (stage.timer) clearTimeout(stage.timer);
stage.inhold = true;
if (callbacks.touchholdstart) callbacks.touchholdstart.call(reciever, e);
};
stage.getContent().addEventListener('touchstart', function(e) {
e.preventDefault();
calcTouchEventData(e);
stage.timer = setTimeout(function() {
stage.onLongTouch(e);
}, touchduration);
if (callbacks.touchstart) callbacks.touchholdstart.call(reciever, e);
});
stage.getContent().addEventListener('touchmove', function(e) {
e.preventDefault();
if (stage.timer) clearTimeout(stage.timer);
if (stage.inhold) {
if (callbacks.touchholdmove) callbacks.touchholdmove.call(reciever, e);
} else {
if (callbacks.touchmove) callbacks.touchmove.call(reciever, e);
}
});
stage.getContent().addEventListener('touchend', function(e) {
e.preventDefault();
if (stage.timer) clearTimeout(stage.timer);
if (stage.inhold) {
if (callbacks.touchholdend) callbacks.touchholdend.call(reciever, e);
} else {
if (callbacks.touchend) callbacks.touchend.call(reciever, e);
}
stage.inhold = false;
});
}
later I call registerStageGestures on a few elements (represented by 'View' objects) in the same page. Something like:
function View() {
var self=this;
..
function InitView() {
...
registerStageGestures(kineticStage, {
touchstart: function(e) {
// do something
},
touchmove: function(e) {
// do something
},
touchendunction(e) {
// do something
},
touchholdstart: function(e) {
// do something
},
touchholdmove: function(e) {
// do something
},
touchholdend: function(e) {
// do something
},
}, self);
Everything works fine, however I'm left wondering about two things in the implementation of registerStageGestures:
First, is it necessary to make inhold, timer and onLongTouch members of the stage ? or will closures make everything works well if they are local vars in registerStageGestures ?
Second, is it necessary to call the callbacks with '.call(receiver,' syntax ? I'm doing this to make sure the callback code will run in the context of the View but I'm not sure if it's needed ?
any input is much appreciated
Thanks!
First, is it necessary to make inhold, timer and onLongTouch members
of the stage ? or will closures make everything works well if they are
local vars in registerStageGestures ?
As far as registerStageGestures() is concerned, var inhold, var timer and function onLongTouch(e) {...}. would suffice. The mechanism by which an inner function has automatic access to its outer function's members is known as "closure". You would only need to set stage.inhold, stage.timer and stage.onLongTouch if some other piece of code needs access to these settings as properties of stage.
Second, is it necessary to call the callbacks with '.call(receiver,'
syntax ? I'm doing this to make sure the callback code will run in the
context of the View but I'm not sure if it's needed ?
Possibly, depending on how those callbacks are written. .call() and .apply() are sometimes used when calling functions that use this internally. In both cases, the first parameter passed defines the object to be interpreted as this. Thus, javascript gives you the means of defining general purpose methods with no a priori assumption about the object to which those methods will apply when called. Similarly, you can call a method of an object in such a way that it acts on another object.
EDIT:
For completeness, please note that even in the absence of this in a function, .apply() can be very useful as it allows multiple parameters to be specified as elements of a single array, eg the ubiquitous jQuery.when.apply(null, arrayOfPromises)...
There are some simple answers, here.
First, closure:
Closure basically says that whatever is defined inside of a function, has access to the rest of that function's contents.
And all of those contents are guaranteed to stay alive (out of the trash), until there are no more objects left, which ere created inside.
A simple test:
var testClosure = function () {
var name = "Bob",
recallName = function () { return name; };
return { getName : recallName };
};
var test = testClosure();
console.log(test.getName()); // Bob
So anything that was created inside can be accessed by any function which was also created inside (or created inside of a function created in a function[, ...], inside).
var closure_2x = function () {
var name = "Bob",
innerScope = function () {
console.log(name);
return function () {
console.log("Still " + name);
}
};
return innerScope;
};
var inner_func = closure_2x();
var even_deeper = inner_func(); // "Bob"
even_deeper(); // "Still Bob"
This applies not only to variables/objects/functions created inside, but also to function arguments passed inside.
The arguments have no access to the inner-workings(unless passed to methods/callbacks), but the inner-workings will remember the arguments.
So as long as your functions are being created in the same scope as your values (or a child-scope), there's access.
.call is trickier.
You know what it does (replaces this inside of the function with the object you pass it)...
...but why and when, in this case are harder.
var Person = function (name, age) {
this.age = age;
this.getAge = function () {
return this.age;
};
};
var bob = new Person("Bob", 32);
This looks pretty normal.
Honestly, this could look a lot like Java or C# with a couple of tweaks.
bob.getAge(); // 32
Works like Java or C#, too.
doSomething.then(bob.getAge);
? Buh ?
We've now passed Bob's method into a function, as a function, all by itself.
var doug = { age : 28 };
doug.getAge = bob.getAge;
Now we've given doug a reference to directly use bobs methid -- not a copy, but a pointer to the actual method.
doug.getAge(); // 28
Well, that's odd.
What about what came out of passing it in as a callback?
var test = bob.getAge;
test(); // undefined
The reason for this, is, as you said, about context...
But the specific reason is because this inside of a function in JS isn't pre-compiled, or stored...
this is worked out on the fly, every time the function is called.
If you call
obj.method();
this === obj;
If you call
a.b.c.d();
this === a.b.c;
If you call
var test = bob.getAge;
test();
...?
this is equal to window.
In "strict mode" this doesn't happen (you get errors really quickly).
test.call(bob); //32
Balance restored!
Mostly...
There are still a few catches.
var outerScope = function () {
console.log(this.age);
var inner = function () {
console.log("Still " + this.age);
};
inner();
};
outerScope.call(bob);
// "32"
// "Still undefined"
This makes sense, when you think about it...
We know that if a function figures out this at the moment it's called -- scope has nothing to do with it...
...and we didn't add inner to an object...
this.inner = inner;
this.inner();
would have worked just fine (but now you just messed with an external object)...
So inner saw this as window.
The solution would either be to use .call, or .apply, or to use function-scoping and/or closure
var person = this,
inner = function () { console.log(person.age); };
The rabbit hole goes deeper, but my phone is dying...

Confused by this - getting error "this.myfuntion() is not a function"

Background: I am trying to edit a zen cart horizontal pop out menu to make the popout open inline within the menu. The problem I am having is that I am struggling to get my head around the javascript/jquery that came with it.
Without posting the whole thing the structure of the code is something like this:
(declare some vars)
//some functions like this:
function funcname(obj) {
//do something
}
//then one big master function like this:
function bigfunc(arg1, arg2, arg3, arg4, arg5) {
//declare some vars based on this
this.varname1=varname1;
this.varname2=varname2;
//declare some functions inside the big function
this.innerfunc1= function() {
//do stuff
}
this.innerfunc2= function() {
//do stuff
}
}//end of big function
//then goes on to declare init function
function initfunc(){
//this creates new bigfunc(arg1 arg2 arg3...) for each main menu item
}
//finally calls init function with
window.onload = initfunc();
Now on to my confusion -
1) firstly for clarification, am I correct in thinking based on all the this's floating about in bigfunc() and the fact that it is called with new bigfunc() that this is creating an object?
2)My current problem is with one of the functions inside bigfunc() which looks like this:
this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
var maxwidth = this.children[0].width;
var nextWidth;
if (this.isMouseOnMe || this.isMouseOnChild()) {
nextWidth = divref.offsetWidth + slideSpeed_out;
if (nextWidth >= maxwidth) {
this.finishOpeningChild(divref, ulref, maxwidth);
} else {
ulref.style.left = nextWidth - maxwidth + "px";
divref.style.width = nextWidth + "px";
setTimeout("slideChildMenu('" + this.getId() + "')", slideTimeout_out);
}
}
Now my plan is to alter this to use jquery show to open the element so I tried this:
this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
if (this.isMouseOnMe || this.isMouseOnChild()) {
$(divref).show(function(){
this.finishOpeningChild(divref, ulref);
});
}
}
But I am getting this-> TypeError: this.finishOpeningChild is not a function
Now, there is a lot of other stuff going on in this js so I wouldnt dream of asking someone on here to do my work for me, but I am hoping that if someone can explain to me why this function is not a function I may be able to work the rest out.
NOTE: I thought this was to do with the scope of "this" but the value of this appears to be exactly the same in both versions of the code.
I know this is a long one but your help is greatly appreciated.
The value of this in a function is called the "context" in which the function runs. In general, whenever you pass a callback function as an argument (as you do with $(divref).show(function() {...})), the function can run the callback in whatever context it wants. In this case, the jQuery show function chooses to run its callback in the context of the element being animated.
However, you want access to the value of this at the time the anonymous callback function is defined, rather than when it is run. The solution here is to store the outer value of this in a variable (traditionally called self) which is included in the scope of the newly-defined function:
this.slideChildMenu = function() {
//...
var self = this;
$(divref).show(function(){
self.finishOpeningChild(divref, ulref);
});
}
I am thinking that the jQuery selector has changed the scope of this.
In your example $(this); would refer to object being animated per jQuery api docs:
If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.
If the object in question is instantiated you can call it with dot notation without using this like bigFunc.finishOpeningChild(divref, ulref);
You're probably a little confused about scope, it's not always easy keeping track, but doing something more like this:
var site = {
init: function(elm) {
self=site;
self.master.funcname2(self.varname1, elm); //call function in master
},
funcname: function(obj) {
//do something
},
varname1: 'some string',
varname2: 3+4,
master: function() {
this.varname3 = sin(30);
this.funcname2 = function(stuff, element) {
site.funcname(element); //call function in 'site'
var sinus = site.master.varname3; //get variable
}
}
}
window.onload = function() {
var elm = document.getElementById('elementID');
site.init(elm); //call init function
}
usually makes it a little easier to keep track.

setTimeout() causing slowdown and not exiting properly

Clarification: The parent frame is Page X, the child frame resides within page X.
The issue is the slow behavior and never hitting the section of code that clears the interval.
I have a parent and chilframe. An object is created in the parent then I used setTimeout() in the childframe to call the parent object to add itself to an internal collection within the parent object.
The code doesn't seem to behave as intended with really slow response from the browser. Any thoughts on the issue?
Parent frame
<script type="text/javascript">
var Cert = new Parent();
</script>
Child frame
<script type="text/javascript">
var c;
var id = setInterval("Create()", 1000);
function Create()
{
if (parent.Cert != null && parent.Cert != undefined)
{
c = new Child(parent.Cert, 1, null);
clearInterval(id);
}
}
</script>
Don't pass a string to setTimeout/Interval. Pass it a function reference instead!
var id = setInterval(function () {
Create();
}, 1000);
From the code you've given here, parent is window. Is this what you intend? There seems to be some relevant code missing here...
As for the slowdown, perhaps the function interval is too short, or it is never being satisfied? There could also be an error in the constructor for the Child class, which would make it so the clearInterval line won't ever be called. You could consider putting a limiter out there, or wrapping your instantiation in a try...catch block, or moving the clearInterval statement above the line where you're creating your object.
Or, do all of those things:
var c = null;
var id = setInterval(function () {
Create();
}, 1000);
var itr = 0;
function Create() {
// if it has looped more than 20 times, forget it
if (itr > 20) {
/* show an error message? */
clearInterval(id);
return false;
}
if (parent.Cert != null && typeof parent.Cert != 'undefined') {
// clear the interval first
clearInterval(id);
// safely create object
try {
c = new Child(parent.Cert, 1, null);
} catch (e) {
/* handle exception here */
}
} else {
// incrementing the interval counter
itr++;
}
}

Categories

Resources