JavaScript - Sub-object Callback Handler Changes 'this'
Hi, I having problems using 'this' in an objects method. I have simplified the problem - see image.
I instantiate object obj1 which inturn instantiates subObj1. subObj1 is a slave to obj1. obj1 registers a handler function called method1 with subObj1 so that subObj1 can tell obj1 when it has finished. For example: call subObj1.subMethod2() to get the sub object to do something. subObj1 calls subMethod1 when its finished with its task, which inturn causes method1 to be called. If I call method1 directly from obj1 'this' refers to obj1. However when method1 gets called by the subObj1 through the event handler mechanism, I find that 'this' has been changed to refer to subObj1. This is a problem as now method1 has lost all connection with its object obj1. If I define method1 within the 'Class1' function, I can get it to work if I use the 'var me = this;' trick, but if you have lots of methods within Class1() with further nesting this can get a bit hard to read. So, can someone tell me how to deal with 'this' changing. I.e. I want 'this' to refer to obj1 within method1. Code: <html> <body> <script type="text/javascript"> function Class1(){ this.prop1 = "prop"; this.subObj1 = new SubClass1(); //sub-object this.subObj1.subMethod1 = this.method1; //register handler } Class1.prototype.method1 = function(){ console.log(this.prop1); } function SubClass1(){ this.prop1 = "subObjProp"; this.subMethod1; this.subMethod2 = function(){ this.subMethod1(); }; } obj1 = new Class1(); obj1.method1(); //prints 'prop' obj1.subObj1.subMethod2(); //prints 'subObjProp' </script> </body> </html> On another note, there seems to many ways of defining methods (e.g using 'prototype' etc etc) and I gettting sick and tierd of a 'trial and error' approach to get things working. Can anyone recomend a good resourse that sets out the best way to design with javascript so I dont keep running into these issues. (E.g. is my scheme of communicating with sub-objects a bit crazy, and is there a better way.) Thanks. Similar TutorialsThe only way I can figure out to invoke an event handler, like onchange or jquery's change, after an ajax response is rendered to page is by triggering event handler within the ajax call. Is there a better way to do this? It looks like bad code but this is only where I am at right now in rendering a table to page and now allowing user filtering: (function($){ var listview = $('#listview'); $('#dashboard a').click(function(){listLoader(this);}) var listLoader = function(context, options){ for(var i = 0; i < arguments.length; i++){ var data = arguments[1] } var url = context.href.substring(context.href.lastIndexOf('#') + 1); $.ajax({ type: 'GET', url: '/' + url, data: data, dataType: 'html', error: function(){}, beforeSend: function(){}, complete: function() {}, success: function(response) { listview.html(response); $("select").change(function(){ var option = $(this).val(); listLoader(context, option); }) //end for change } }) } })(jQuery) So I hacked up a version of the wowSlider to work as a timed rotating background... I need to know how to add a callback funtion so that I can make the Image and link that is in front of the wowSlider to change each time the background changes. Here is what I have so far: http://www.eclipse2.com/testing/new_layout/ Help would be greatly appreciated. I'm updating a database w/o "reloading" the page using jquery & ajax. Everything works fine, but I need to display an error (in php - mysql_error()) in the error callback function. I also don't think that the success/error callbacks are working as even when I changed the password in to the mysql server in the php file, I got the success message :S Can any1 help me out? this is the php script Code: <?php /*$fp = fopen('data.txt', 'a+'); fwrite($fp, 'ok'); fclose($fp);*/ $sections = $_REQUEST['sections']; $fontColor = $_REQUEST['fontColor']; $bgcolor = $_REQUEST['bgcolor']; $font = $_REQUEST['font']; $fontSize = $_REQUEST['fontSize']; $lineHeight = $_REQUEST['lineHeight']; $letterSpacing = $_REQUEST['letterSpacing']; $fontStyle = $_REQUEST['fontStyle']; //$tekst = $_REQUEST['tekst'] $connect = mysql_connect("localhost", "root", "password") or die ("Unable to connect to the database"); mysql_select_db("ipsum") or die ("doesnt exist: " . mysql_error()); $update = "INSERT INTO con (Sections, Fontcolor, BackgroundColor, Font, FontSize, LineHeight, LetterSpacing, FontStyle) VALUES ('".$sections."', '".$fontColor."', '".$bgcolor."', '".$font."', '".$fontSize."', '".$lineHeight."', '".$letterSpacing."', '".$fontStyle."')"; // the content of 'data.txt' is now 123 and not 23! mysql_query($update) or die ("unable to update: " . mysql_error()); mysql_close($connect); ?> and this is what I currently have for the error Code: error: (function (){$('#errorMessage').fadeIn("slow").delay(1000).fadeOut(2000);}), but that needs to change... so, I should start by saying that I don't really understand callbacks (but I understand what they do), and here's the thing: html5 browser geolocation has an error callback which works fine EXCEPT if the user is using FF and refuses to share their location. In IE and Chrome, this produces a "permission denied" error which you can then handle. But firefox just sits there because it never receives the error. Here's an example - click on Not now in FF to see what I mean. So the only solution I can see is to make some special case for FF and this is where my question comes in - can I set a condition within the callback that says something like if it wasn't successful, but you didn't get an error, do this... I thought that if (!position&&!error) {useMaxMind("Firefox fallback"); } might do it, but it can't go in the error callback (I guess because that only fires if an error is detected) and it doesn't work in the main function (I guess because if that code runs it means the location has been found)... anyway. Here's what I have for the moment, which just sets a timeout as soon as it loads. It would be nice to have something a bit more elegant, though. thanks in advance... Code: function initialize() { // try W3C standard approach var geoTimeout = 10000; var timeOuthandler = setTimeout("useMaxMind('Timeout')", geoTimeout); if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latLong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); alert("geolocation successful"); clearTimeout(timeOuthandler); showMap(latLong, 16); }, function (error) { switch (error.code) { case 0: message = "Something went wrong: " + error.message; break; case 1: message = "You denied permission to this page to retrieve a location."; break; case 2: message = "The browser was unable to determine a location: " + error.message; break; case 3: message = "The browser timed out before retrieving the location."; break; } clearTimeout(timeOuthandler); useMaxMind(message); }, {timeout:geoTimeout} ); } else { useMaxMind("No browser support"); } } Could somebody help me please to explain what I'm doing wrong.... a have this html file with references to some javascripts (datagrid from http://www.datatables.net) and this html file work ok..I mean javascripts a css styling works with table... but when I call this page by ajax and callback (this html page) is forward back into another div , table doesn't work ....just data from page but now functionality from javascript and css styling... how should I force callback result to use javascript and css? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml"> <style type="text/css" media="screen"> @import "media/css/demo_page.css"; @import "media/css/demo_table.css"; @import "http://www.datatables.net/media/css/site_jui.ccss"; @import "media/css/demo_table_jui.css"; @import "media/css/themes/base/jquery-ui.css"; @import "media/css/themes/smoothness/jquery-ui-1.7.2.custom.css"; /* * Override styles needed due to the mix of three different CSS sources! For proper examples * please see the themes example in the 'Examples' section of this site */ .dataTables_info { padding-top: 0; } .dataTables_paginate { padding-top: 0; } .css_right { float: right; } #example_wrapper .fg-toolbar { font-size: 0.8em } #theme_links span { float: left; padding: 2px 10px; } </style> <script type="text/javascript" src="media/js/complete.js"></script> <script src="media/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script> <script type="text/javascript" src="media/js/jquery.dataTables.editable.js"></script> <script src="media/js/jquery.jeditable.js" type="text/javascript"></script> <script src="media/js/jquery-ui.js" type="text/javascript"></script> <script src="media/js/jquery.validate.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready( function () { $('#example').dataTable().makeEditable({ sUpdateURL: "update.php", sDeleteURL: "delete.php" }); } ); </script> </head> <body id="index" class="grid_2_3"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th> ID</th> <th> user</th> <th> password</th> <th> first</th> <th> last</th> <th> company</th> </tr> </thead> <tbody> <tr class="even_gradeA" id="1"> <td> 1 </td> <td> XY </td> <td> passwoed </td> <td> Ja </td> <td> jajovic </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="2"> <td> 2 </td> <td> jojo </td> <td> fa25af5301e2dda1fddea740200aa10ab6c70d86 </td> <td> jojo </td> <td> jojovicko </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="3"> <td> 3 </td> <td> kuk </td> <td> d588aebb93e3adf70eac1fb479d6d53f9dc21816 </td> <td> kuk </td> <td> kukovic </td> <td> 3 </td> </tr> <tr class="even_gradeA" id="10"> <td> 10 </td> <td> admin </td> <td> f865b53623b121fd34ee5426c792e5c33af8c227 </td> <td> admin </td> <td> adminovic </td> <td> 3 </td> </tr> </tbody> </table><button id="btnDeleteRow">Delete</button> </body> </html> I have a project that uses and Ajax call but it appears that the call back function cannot take arguments, nor return values. However, I have wrapped another function inside the call back function that takes xmlhttp.responseText as the argument and returns values that are supposed to be placed in a global array. If I do, for instance: callback function code.... globalArray = someFunction(xmlhttp.responseText) alert(globalArray), I get the expected values. but a function is called later to query the contents of the global array the global array is empty (No other code or functions exist in this project to alter the global array) Primary dev client is FireFox 3x on Mac OSX Is this a bug, or is there some other aspect of javascript that I need to know about? I am using ajax here because javascript does not have an array shuffling function and php does. So I send an array to the server, have it shuffled by the server and returned to the requesting page. Hi, I have the following code. This code is working fine in FF but not in IE. Can any one let me know how i can resolve this. function handlerFunc (elem, elem1) //elem1 is id of input tag { elem.onKeyUp = keyupHandler (elem1); //throwing error in IE. If i remove argument it is working fine, but i want to make it work with arguments. } function keyUpHandler (elem1) { alert (elem1.form.name); } Hi all, I am really stuck on this: I have an iframe on my page <iframe id="displayframe">. I used security="restricted" to create a more 'secure' frame but that means that any forms which submit will be opened in a new window... away from my website. I also have a textbox, called "showurl" which acts as an 'address bar' to the iframe and the accompanying button "go". I read on Stanford's website that: "It is possible to use JavaScript inside the restricted iframe, by attaching event handlers from the outside (unrestricted) window. This allows the outer window to get around the restriction that hyperlinks in a restricted iframe are supposed to open in a new window. " So I would need a function that would detect when a new page has been opened (ie. a form has been submitted) and would be able to take the URL of the new page, copy the new page's URL into the textbox and click the button "Go" and close the new page (the one which just opened) All in all... The event handler needs to get the url of the submitted form page (the opened window) paste it into the textbox "showurl", click the button "go" and then close the opened window. Could anyone help me out on this? It would be greatly appreciated!! if it is done like this: Code: anElement.onclick=handleIt; function handleIt() { this. ... //'this' refer to the anElement } However, if you attach an event, quirk happens: Code: anElement.attachEvent("onclick",handleIt); // not sure if anElement.addEventListener("click",handleIt,false) works well function handleIt() { this. ... //'this' refer to an empty object ??????? } why 'this' doesn't refer to the current target? anyone can help? Just want to be sure - I am trying to install cufon scripts and apparently we should "Add JavaScript error handling in case there is an error loading" Is this done like the following: Code: <script type="text/javascript"> function handleError() { return true; } window.onerror = handleError; </script> Thanks Hey Everyone, I would like to let a select menu drop down with the click of a button or image. So, I have: Code: <select> <option>Option1</option> <option>Option2</option> <option>Option3</option> <option>Option4</option> </select> So, how do I trigger this select menu to drop down, except for clicking on the down arrow? Thanx in forward I understand that there is an onended event handler that can be used to detect when a media event, such as the playing of am MP3 file or digital video file, is completed. I would like to know 1. how to use code this event handler and 2. how to use detection of the end of the media event to launch another Web page. Thanks for any help, George I have many examples within my page of the form: Code: <a id="L1" href="#" onclick="return showSpan();" onblur="return hideSpan();"><span> ... </span></a> The page is styled so that hovering over the link displays the contents of the hidden <span> as a block without any javascript. I want this to work (that is display the span as a block) when the user tabs onto a link (and presses Return/Enter). When the user tabs away, it should hide the <span>. My starting code looks like: Code: function showSpan() { var linkID = document.getElementById(this.id); var classList = linkID.getElementsByTagName('span'); var divID = classList[0]; divID.style.display = "block"; return false; } // function with a similar function for hideSpan(), Ultimately I would like to add these event handlers in the initialisation phase, which is why I have used a parameterless function. Whenever I try this, I get an error that this.id does not exist. How can I attach these event handlers? John Rostron hello everyone, i am new to all this.. i need help regarding.. i am generating text box dynamically(mean it's a multiple select box, depending upon the number you select , it will generate that many text field.) my problem is that i want to assign a calender to the text field generated whenever a user clicks on that text field. i am able to do it for simple text field as onclick="javascript: showCalendar('idname')" but how to do it in this case, where can i declare this ? Hey guys, I know that there are two ways to declare an event in javascript. 1.Inline ie: <a href="#" onclick="function_name(param)">Link</a> 2.Traditional ie: linkelement.onclick = function_name; Now, how can the second method work with functions that have parameters??? Since we can't use parenthesis, how do we pass in the arguments?! Hello all, I'm wondering if anyone can offer advice on a simple (or so I thought!) Javascript menu I'm trying to create. I'm creating 5 buttons, using event handlers (onmouseover etc) which exchange 1 image for another. I did the first one fine - it worked perfectly, but as soon as I added the rest they all stopped working properly. The best I have got, is that the last link will do what it's supposed to regardless of which link I hover over! Which is strange. So the browser seems to be actioning the last thing on the list if that makes sense. It seems to me that I need to add an "if" type attribute, so "if" I hover over the home button, the home images change, as opposed to the last one on the list. This is the code I have so far for a single link - the rest are copies of this with adjustments made to the imgname and image sources obviously..... <div style="width:80px; height:20px;margin-top:20px;margin-left:85px;"><a href="about.html" onMouseOver="return changeImage()" onMouseOut= "return changeImageBack()" onMouseDown="return handleMDown()" onMouseUp="return handleMUp()" ><img name="aboutbutton" src="img/aboutn.png" width="80" height="20" border="0" alt="javascript button 1"></a> <script language="JavaScript"> upImage = new Image(); upImage.src = "img/abouth.png"; downImage = new Image(); downImage.src = "img/aboutc.png" normalImage = new Image(); normalImage.src = "img/aboutn.png"; function changeImage() { document.images["aboutbutton"].src= upImage.src; return true; } function changeImageBack() { document.images["aboutbutton"].src = normalImage.src; return true; } function handleMDown() { document.images["aboutbutton"].src = downImage.src; return true; } function handleMUp() { changeImage(); return true; } </script></div> Any suggestions on where I am going wrong would be wonderful. Thanks so much in advance! All the best I'm having trouble passing an array into an event handler. This does not work: Code: var lightbulb = [1,1,1,0,1,0] var banana = [0,0,1,1,0,1] function changetextimage(arr){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (arr[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } $('#lightbulbpicture').mouseover(changetextimage(lightbulb)); $('#bananapicture').mouseover(changetextimage(banana)); This does work: Code: var lightbulb = [1,1,1,0,1,0] var banana = [0,0,1,1,0,1] function changetextimage1(){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (lightbulb[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } function changetextimage2(){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (banana[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } $('#lightbulbpicture').mouseover(changetextimage1); $('#bananapicture').mouseover(changetextimage2); I have a whole bunch of these arrays (which are much longer) that I want to pass into this function so I just want to pass each as an argument rather than write each function out. I bolded the areas I'm talking about so it's easier to see. Please help me with this code to determine whether the check box has been checked. I get "Thank you" even if I don't check the check box. <script type="text/javascript"> var uncheck = document.getElementById().checked == false; var accept; function checkAccept() { var uncheck; if (uncheck == false){ alert ("You must accept the terms."); } else (uncheck == true) { alert ("Thank you."); } } </script> <form> <br />Please accept the terms by clicking the box below: <br />Accept terms: <input type="checkbox" id="accept" value="Y" /> <br /><input type="button" name="btn" value="Accept" onclick="checkAccept()" /> </form> </body> </html> Q1. write a function called countAS that will take a string as input (using a prompt dialog box,prompt the user or the string).the string must contain only a's,b's and c's e.g. "abccbbaa" or "aaabbbccc" if any other letters are present apart from the letters a b c, output an alert dialog box with an error message and prompt the user again to input a valid string.count the number of a's the numbers of b's and the numbers of c's entered and display the count for each as well as a total count of all the characters within the string . for example if the string was abbcc output should be as follows: the total count is 5 characters The Number of a's is 1 The Number of b's is 2 The Number of c's is 2 Q2. write a code that uses an event handler to display an alert dialog box with the message 'hello to you all' when a user clicks a link in a html page which links to the school of computing website. |