Objects, Callback Functions And Variable Scope
Nov 23, 2005
I am trying to convert some of my javascripts into a class and am
running into difficulties which i think are related to variable scope.
Basically I have a constructor function for a calendarInput class that
takes 4 parameters, the first is a reference name/number for this
input. I also have some functions for importing my PHP classes into
Javascript using AJAX (properties only. still trying to get methods
working but that's another story!). The relevant function is called
call_object_method(classname, methodname, createparams, methodparams,
post, callbackfunction). This creates an instance of the specified PHP
class using the parameters in createparams. It then calls the
specified method using the parameters in methodparams. The result is
passed back to the javascript function specified in the callbackfunction parameter (ie the value of xmlhttp.onreadystatechange is set to callbackfunction before xmlhttp.send() is called)
The function i am trying to fix is called show (x,y) which creates the
html for the calendarInput and displays it at co-ordinates x, y.
So, my code is as follows:
function calendarInput(calendarid, target, displaytarget, value)
{
this.calendarid = calendarid;
this.target = target;
this.displaytarget = displaytarget;
this.value = value;
this.show = function(x, y)
{
<!--// bunch of init and prepping code. includes creating
createparams and methodparams arrays //-->
call_object_method("cms_calendar", "getcalendarview",
createparams, methodparams, false, this.showcallback);
}
this.showcallback = function()
{
alert(this);
<!--//code to create html//-->
}
}
I know i've cut out most of the innards of this. This is because I
have already tested these functions and had the calendarInput working
outside of a class, hence am pretty sure that this is ok (plus it runs
to almost 1000 lines these days!!). My problem is that when I call the
show method, the alert on the first line of the callback function
returns the function showcallback instead of (as i was expecting) the
instance of the calendarInput object. Whilst this kinda makes sense I
can't figure out how to reference the Object instead. I have tried
'this.parent' but this returned undefined. I have tried changing the
way i reference the callback function (ie the final parameter of
call_object_method) but no joy.
View 2 Replies
ADVERTISEMENT
Mar 17, 2011
I have many forms on a page. When a user click on a new or upate link, releated forms shows up in a dialog box and i validate it .
What my problem is i after i validate the forms i want them to go to it's own callback. Every callback functions is different according to forms.
How can i set different callbacks to each process.
Code below isn't work exactly. It always alert "test1";
Code JavaScript:
// JavaScript Document
var process = function() {
this.url ="";
[Code].....
View 2 Replies
View Related
Aug 23, 2010
I've recently started developing javascript using jQuery and so far I'm really enjoying it.Being a professional programmer (mainly C, C++, java and python) there is one thing that's been puzzling me regarding variable scope and unnamed function declarations. Let me exemplify:
------------------------
var sum = 0;
$(xmlobj).find("item").each(function(){
[code]....
View 6 Replies
View Related
Jul 25, 2011
I think the last thing people seem to learn about in JavaScript when they're not coming from other programming languages is variable scope. Some even get all the way into AJAX without having learned about scope, and this is a time when it's really needed. Although the scope of JavaScript variables is non-complex by nature, it's something we should all get a full understanding for before we move too far.
Section 1: What is "scope"?
Section 2: The "var" keyword
Section 3: The "this" keyword
Section 4: Closures or "Anonymous functions and self-invoking closures
View 5 Replies
View Related
Mar 23, 2010
I am using Ben Alman's JQuery resize plugin in order to obtain the varying computed width of an element when the window is resized (the element in question is a page wrapper that exhibits the expand-to-fit behavior of a block box, and it's computed width is obviously influenced by the resizing of the window. Essentially, what I need to be able to do, is to reference a variable that is defined in a .resize() function ('width_page') in a seperate .each() function.
[Code]...
I now understand that variables can't cross boundaries like in the example above, which leaves me a little stuck. I also understand that this is specific to the context of the .resize() function, and that it can't be taken out of it without using an element selector. Is there some way I can call the .resize() function in my .each() function?
View 3 Replies
View Related
Jun 26, 2007
In the method nextImage, I can't figure out how to access thumbs. It keeps coming back as undefined. (Using Firefox)
function runPortal(portal_number){
// there are multiple runPortals on each webpage
this.portal = document.getElementById('portal'+portal_number); // represents the div that holds the images
this.thumbs = this.portal.getElementsByTagName('a').length; // represents all the images within the div that will be rotated
this.length = this.thumbs.length; // that's how many images will be rotated
// Hide everything
for (var j=0;j<this.thumbs.length;j++){
if (j==0) continue; // Don't hide the first one
this.thumbs[j].childNodes[0].style.display = 'none'
}
this.nextImage = function (){
// there are a fixed number of images to rotate. Start over
if (this.i >= this.length){
this.i = 0;
}
// One fades away, the next appears
Effect.dglPuff(this.thumbs[this.last].childNodes[0], {duration:.6, from:.7});
Effect.Appear(this.thumbs[this.i].childNodes[0]);
// iterate to the next image for the next run
this.last = this.i;
this.i++;
}
// Set up the image rotator
// here is where I started guessing
// thumbs needs to belong to the object rotator, I guess.
this.rotator = new PeriodicalExecuter(this.nextImage, 4); // This object runs the function every 4 seconds
this.rotator.portal = document.getElementById('portal'+portal_number); // represents the div that holds the images
this.rotator.thumbs = this.rotator.portal.getElementsByTagName('a'); // represents all the images within the div that will be rotated
this.rotator.length=this.length; // that's how many images will be rotated
this.rotator.i=0; // the counter for what image we're one
this.rotator.last=0; // the counter for the previous image
}
View 5 Replies
View Related
Feb 9, 2011
This could appear under Ajax, for example, you could have multiple objects that make a singular ajax call (say an RPC-like request) and you need to update the object that made the call during the callback with the result, but it doesn't have to be. The particular problem I'm thinking about happens to be ajax, particularly with multiple objects accessing the same ajax request (meaning I can't use a global or temporary variable).
One way that seems like it would work (just thinking about it in my head), is to create a hash, and to pass the key through the request, store the key in the response, and pick it up on the callback side. Then remove the item from the hash when done.
View 5 Replies
View Related
Jun 7, 2009
I'm trying to create an endless animation similar to a screen saver, here an image floats around the screen, fading in and out. I would like to stay out of the global namespace, so I'd like to use the callback to animate() rather than getTimeout(), which seems to operate only on functions in the global namespace. Please correct me if I'm wrong about that. But I'm having trouble maintaining the scope I want for the callback I want "this" to refer to my Animation object, not the HTML element. I understand many folks have solved this problem for events by using bind() or live(), but I am wondering how to do this for animate().
[Code]...
View 8 Replies
View Related
Aug 11, 2004
Here's the situation: I have a javascript object for controlling a custom DHTML scrollbar. So that I can use more than one on a page, the event listeners need to be passed a reference to the particular instance of the object that each needs to connect to, but as I discovered the hard way, inside an event listener, 'this' returns a reference to the DOM object throwing the event, rather than to the JS object. Short of coming up with a linked list of different objects and having the event handler search through it for the right object when an event is generated, then writing a reference to that object to some global variable, is there any convenient way to tie this together? I hope I've made myself clear enough...
View 5 Replies
View Related
Jul 12, 2009
I'm trying to learn more about creating and using JavaScript objects and ran into this situation the other day:
Code:
function someObject() {
var size = "large";
[code]....
View 5 Replies
View Related
Mar 19, 2011
I have got this piece of code:
Code:
I would like to display the number 1 at first and then 2. but this code produces number 2 for both alerts. I was able to achieve what i wanted with "new" constructor when creating functions but this is not a good practice and after all i am passing these functions as an event handlers and it can't be done with "new" keyword because it is throwing error. I think there are some solutions with arrays e.g the x would be an array of numbers, but i don't like it. Am i missing something important?
View 3 Replies
View Related
Feb 3, 2011
I am using quicksand, i want to use tool tips in it, but i am facing problem due to callback code that i am not able to implement, this is the place where quicksand is present and also told about tooltips usage with it, well he has not explained it in detail as expects people to know jquery before using it. http:razorjack.net...-and-demos.html
the code which is saying to use is this [code]...
i don't know where to place this code and how as i don't know jquery, and if this code is to be place in tooltips script then where to place in it and how, e-g i might use this one[code]...
then in this code where to put the above code.
If its not possible with the above tooltip then i am ready to use any tooltip which can display picture in it.
View 4 Replies
View Related
Feb 1, 2011
well i am using quicksand, i want to use tool tips in it, but i am facing problem due to callback code that i am not able to implement, this is the place where quicksand is present and also told about tooltips usage with it, well he has not explained it in detail as expects people to know jquery before using it the code which is saying to use is this
$("#content").quicksand($("#data > li"),
{
duration: 1000,
[code]....
View 14 Replies
View Related
Jul 20, 2005
If I do . . .
myForm=document.tstForm;
function initialSetup(){
myForm.fld01.value="Test 01"
myForm.fld02.value="Test 02";
myForm.fld01.focus();
}
Then, in the body tag, I do onLoad="initialSetup()",
the script doesn't work and I get a "myForm has no properties" error
I know it'll work if I move it within the function, but I figured a
global variable would retain its value within the function. Why not?
View 2 Replies
View Related
Jul 23, 2005
Given the following working code:
function attributes() {
var attr1 = arguments[0] || '_'
var attr2 = arguments[1] || '_'
return (
function (el1, el2) {
var value1 = el1[attr1] + el1[attr2];
var value2 = el2[attr1] + el2[attr2];
if (value1 > value2) return 1;
else if (value1 < value2) return -1;
else return 0;
}
);
}
var a = [
{ a:'smith', b:'john' },
{ a:'jones', b:'bob' },
{ a:'smith', b:'jane' }
];
a.sort(attributes('a', 'b'));
for (var i =0; i < a.length; i++) {
document.write(a[i].a + ', ' + a[i].b + '<br>');
}
My question is, are attr1 and attr2 guaranteed to exist through
the lifetime of a.sort(attributes('a', 'b'))?
As I understand it, the anonymous inner function reference I am
returning is a property of attributes(). As such, when I return a
reference to the anonymous inner function, the outer attributes()
function must continue to exist (as must attr1 and att2) until
there are no further references to the inner anonymous function.
As a result, there is no danger of attr1 or attr2 "disappearing"
during the repeated calling of the anonymous inner function.
Is my explanation basically correct, or am I deluding myself and
I'm just lucky that the garbage collector hasn't recovered attr1
or attr2 while the sort is still going on? In other words, is the
behaviour I'm seeing consistent and predictable, or should I
change my approach?
View 3 Replies
View Related
Apr 24, 2006
I am struggling to find examples on the web that implement Javascript
callback functions of an embedded Real Player.
There are lots of examples for Visual Basic, but I couldn't find any for
Javascript.
I am looking for any basic example.
For example, showing a javascript alert when a Real Player error is
triggered. (with examples for both Netscape/Firefox and Internet Explorer)
View 2 Replies
View Related
Jan 2, 2012
I am writing a small module which will have several different aspects to it, all based around ajax calls. I want to allow the main ajax functions i.e beforeSend, success, complete etc (I am using jQuery) to be customizeable.I currently have an options object in the module which can be extended with an options object passed to an init function. In here, I am passing a 'callbacks' object with nested ojects for each different type of action as in...
var insertCallbacks = {
before : function() {
},
success : function() {
[code]....
View 2 Replies
View Related
Oct 30, 2006
I think I've had JavaScript variable scope figured out, can you please
see if I've got it correctly?
* Variables can be local or global
* When a variable is declared outside any function, it is global
regardless of whether it's declared with or without "var"
* When it is declared inside a function, if declared with "var", it's
local, if not, it's global
* A local variable that is declared inside a function is local to the
whole function, regardless of where it is declared, e.g.:
function blah() {
for(var i ... ) {
var j ...
}}
i and j will both be visible within blah() after their declaration.
* the notion of "function" in this context also applies for this kind
of construct:
var myHandler =
{
onClickDo: function()
{
in the sense that whatever one declares inside onClickDo with "var"
will only be visible inside onClickDo. What else, am I missing anything?
View 4 Replies
View Related
Jun 14, 2010
I've created a jQuery script that uses a switch statement. However, my experience with it, relative to variable scope, doesn't seem to follow the logic.According to the JavaScript/jQuery theory, a global variable was accessible (meaning read & write) throughtout any function within any script (one that page).However, apparently that theory wasn't completely true as it pertained to switch statements that contained variables. To illustrate my case in point, I've included a simplistic version of my code:
$("#selector").delegate("div", "click", function(event) {
var testVar = 4;
switch (this.id) {
[code]...
As shown, the variable "testVar" is not accessible from one case to the next case .Furthermore, to add insult to injury, I am seeing the same behavior within the conditional if else statement counterpart to the switch statement.
View 1 Replies
View Related
Oct 17, 2010
I have this web application where users are able to fill out and submit reports. The reports and scripts are part of a whole system, that is, they are used on a couple of different clients written in both vb and c#. This is the web-version of those clients.The scripting language is javascript and is executed using different script engines on the different systems. But for the web-version it is just executed in the browser.The different fields in the report can be accessed by typing:ID1.value. To get ID1 to apply for the input-field with id ID1 I had to in the initfunction of the page write a window["ID1"] = document.getElementById("ID1");
But my problem is when this element change. Cause in the report I have a special element that in the browser is translated to a table-element with a report-field in each cell.When I switch the current row, I need to update the window["ID1"] to equal the correct report field on the selected row. But when trying to access the new variable ID1 from a buttons onclick event it is undefined.<input type="text" id="test" onclick="alert(ID1.value);" />What I think happens is that when the page is first drawn the onclick event is created and as I understand, variables inside an event has the same value as when the event was created.
So if ID1.value was something when the page was created it will be the same when it is called even if the value of ID1 is different. And that seems to be the case. When I debug the page, before entering the event, ID1.value has the correct value while inside the event it is undefined and after the event it has the correct value. If I write window["ID1"] correct value is also shown.But a weird thing is that in another place in the code I had the same problem but instead of having the code inside the onclick event I first had a global function changeActiveRow and inside that I had an eval, eval(document.getElementById("ID1_script")) where ID1_script is a hidden element whos value is a script using ID1.value and that works.
View 3 Replies
View Related
Jun 2, 2011
for some time I always found a workaround for this kind of problem. But somwhow, it feels wrong. So I'd like to know, if there's a common way to solve something like this[code]...
I'm defining the function and if the value of 'obj' hasn't until the function really gets called, this can work. But it just feels so wrong do have always global variables just to access them inside of a callback.[code]...
View 4 Replies
View Related
Oct 27, 2009
I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me.
I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself.
I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time.
[Code]...
View 2 Replies
View Related
Jan 31, 2011
[code]how i can set context/scope for myStartAction so it can access (this.url) variable?console.log(dd.url) will work but i can't predict what name will object have (that depends on user) there might be more than one instance of myObject
View 10 Replies
View Related
Oct 13, 2009
a.) specify two parameters for the changeYear function: today and holiday.
function changeYear(today)(holiday){
b.) in the first line of the above function, use the getFullYear() date method to extract the 4-digit value from the today variable and store the value in a variable named year.
first line
c.) in the second line; use the setFullYear() date method to set the full year of the holiday date object to the value of the year variable.
second line
d.) in the third line, use a conditional operator on the year variable. The test condition is whether the value of the holiday date object is less than the today date object. If it is, this means that the event has already passed in the current year and the value of the year variable should be increased by 1.
third line
e.) in the fourth line of the function, again set the full year value of the holiday date object to the value of the year variable.
View 3 Replies
View Related
Jun 2, 2010
I have a toggle animation which puts the area I want to show to the user in view, ones that animation has played I want to animate several other objects on the page. I have the code to animate one object by using the callback function in animate. But is it possible to animate several objects in the callback function?. this is the code I have so far
$(document).ready(function(){
$(".navigaat").toggle(function(){
$(".mover").animate({left: '0px' }, 'slow',"", function() { $(".blok").animate( { fontSize:"160px" } , 1000 )});
[code]....
View 4 Replies
View Related
Nov 10, 2011
What I did wrong to make this code not work. Can you put a variable in a function callback?
<script type="text/javascript">
var aaa = prompt('number?')
var obja = new Const(aaa);
functin Const(numb){
this.x=numb;
alert(obja.x);
}
</script>
View 3 Replies
View Related