JavaScript - Giving An Object A Custom Value
Hi all.
I'm developing After Effects scripts using their Extendscript language - essentially just Javascript with various extensions. I've defined a class, called ScriptSetting, which handles reading and writing of user settings to a prefs file. For example I create a ScriptSetting variable as follows: Code: var mySetting = new ScriptSetting("myScript", "thisSettingKey", 200); This calls the ScriptSetting constructor function: Code: function ScriptSetting(sectionName, keyName, defaultValue) { this.sectionName = sectionName; // Store the type of this setting for conversion later this.defaultType = defaultValue.constructor; // Convert any type to a string value for storing defaultValue = defaultValue.toString(); this.keyName = keyName; if(!app.settings.haveSetting(this.sectionName, this.keyName)) { this.value = defaultValue; this.saveSetting(); } else this.value = this.getSetting(); } This calls some of Extendscript's built-in functions, like app.settings.haveSetting() This all works fine - I can then later access mySetting's value with, for example alert(mySetting.value) since I've defined value as part of the class constructor function. However what I'd ideally like to do, if at all possible is to lose the .value part and just be able to access the setting value directly from the setting variable, so in this case alert(mySetting). At the moment, this will just return object Object. Naturally this is because mySetting is an instance of the ScriptSetting object. But I wondered if you can spoof this with a different type (i.e. Array or Number) when accessing it as part of a statement e.g. if(mySetting == 200) { // do something } but still retain all its prototyped methods, e.g. Code: mySetting = 300; mySetting.saveSetting(); Is this possible in Javascript? It's not a deal-breaker - I just want to make my code a bit more readable. Many thanks in advance, Christian Similar TutorialsI'm trying to understand how a custom object can call a function within itself. Say I have something like this: Code: function functiontest() { this.prop1 = '', this.prop2 = '', this.options = {initiallevels:0}, this.prop3 = '/blah', this.prop4 = true, this.function4 = function(x) { console.log(x) }, this.init = function(options) { this.uid=options.uid this.t=options.target document.getElementById(this.t).addEventListener('click',function(){this.uid.function4(this.t)},false) } } myfun1=new functiontest myfun1.init({uid:'myfun1',target:'target1'}) myfun2=new functiontest myfun2.init({uid:'myfun2',target:'target2'}) And the html: Code: <html> <head></head> <body> <div id="target1">T1</div> <br> <div id="target2">T2</div> </body> </html> I don't know what to put in the part in bold to set the click event listener and have it call function4 within the functiontest object. I've tried a bunch of different things and nothing worked. Please help, thanks! Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); Ignore post (if mod, please delete)
Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Hi I'm using an image hover script so when you mouseover a thumbnail it displays a larger version of the image in a javascript/jquery nice image popup (not a popup window but like a floating image). It comes from the script here http://cssglobe.com/lab/tooltip/02/ The trouble is, I need the large image to display above and to the left of the thumbnail - not to the right and below. Looking in the js file I see these values: Code: this.imagePreview = function(){ /* CONFIG */ xOffset = 10; yOffset = 30; // these 2 variable determine popup's distance from the cursor // you might want to adjust to get the right result I've tried making these -500 and -500 but it just makes them like the negative value was not added (the large image goes down 500px). So as I don't understand javascript code I'm thinking that is not the way to give a negative number? Would appreciate any help please When i did a view source , checkbox names are displayed as MedicalAction_listOfTransfers_[0]__rowSelected' so each checkbox has different name and id as well all i am trying to do here is to put a checkall/uncheckall option , also in the jsp page we have a pagination so is that something that cause the checkbox value as null ? function MoveAll(){ var lengthofRecords = document.getElementById('resultsSize').value; for (i = 0; i < lengthofRecords; i++){ var name = 'MedicalAction_listOfTransfers_'+i+'__rowSelected'; var checkBox = document.getElementById(name); alert("check box B4: " + checkBox); - // I AM GETTING NULL VALUE HERE checkBox.checked=checkBox.checked == false ? true:false; alert("check box A4: " + checkBox.checked); //checkBox.checked = checkBox.checked? true:false; } } Please help i am newbie In the routine below I'm trying to make sure a date isn't > today. It WORKS FINE in Firefox but I get a NaN in MSN. WHY? And how do I fix it? Thanks Note: ( 2010 2 1 is in testfield and 2010 4 20 is in todayfield) var todayfield = tdyear+" "+tdmonth+" "+tdday; alert ("today=" + todayfield); alert (Date.parse(testfield)); alert (Date.parse(todayfield)); if (Date.parse(testfield) <= Date.parse(todayfield)) How do I store how many Windows my house has as a variable as this script I made isn't working. Quote: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript"> var test function show_prompt(a_bac) { prompt(a_bac) } function show_alert(a_baf) { alert(a_baf) } </script> <body> <!-- How do I store how many Windows my house has as a variable? --> <input type="button" value="click" onclick="var theanswer = prompt('How many windows does your house have?')" /> <input type="button" value="answer" onclick="alert(theanswer)" /> </body> </html> Does anyone know how to make these things work? I have to make this hanjie puzzle and I have at least gotten the black squares to display. I have worked through all the directions three times and run it through the Firebug. I don't understand what it is asking for and don't know how to change the code to make this work, someone please help me! Code: window.onload = setPuzzle; var allCells = new Array(); function setPuzzle() { var puzzleTable = document.getElementById("puzzleCells"); allCells = document.getElementsByTagName("td"); for (var i =0; i < allCells.length; i++) { allCells[i].style.backgroundColor = "white"; allCells[i].onclick = changeColor; } document.getElementById("solution").onclick = showSolution; document.getElementById("hide").onclick = hideSolution; document.getElementById("solution").onclick = showSolution; document.getElementById("check").onclick = checkSolution; document.getElementById("uncheck").onclick = uncheckSolution; } function changeColor(){ this.style.backgroundColor = (this.style.backgroundColor == "black") ? "white" : "black"; } function showSolution(){ for(var i=0;i<allCells.length; i++) { if(allCells.className == "dark"){ allCells[i].style.backgroundColor = "black"; } else { allCells[i].style.backgroundColor = "white"; } } checkCount = 0; } function hideSolution() { for(var i=0;i<allCells.length; i++) { allCells[i].style.backgroundColor = "white"; } checkCount = " "; } function checkSolution() { var checkCount = 0; for (var i = 0; i< allCells.length; i++) { if (allCells[i].style.backgroundColor == "black" && allCells[i].className != "dark") { allCells[i].style.backgroundColor = "red"; } else if (allCells[i].className == "dark" && allCells[i].style.backgroundColor == "white"){ checkCount++; } return checkCount.value; } } function uncheckSolution() { for (var i = 0; i< allCells.length; i++) { if (allCells[i].style.backgroundColor == "red") { allCells[i].style.backgroundColor = "black"; } checkCount = " "; } } All, I have the following code: console.log("My num is: " + num); console.log("My lat is: " + lat); console.log("My lat length is: " + lat.length); console.log("My long is: " + long); When I get the output, I get the following: My num is: {"1":1,"2":2} My lat is: {"1":"40.59479899","2":"41.4599860"} My lat length is: 36 My long is: {"1":"-75.5549650","2":"-87.596430"} I'm confused on why the length is saying 36 when it's obviously two and the other output shows that??? I was wondering if there was any way I can give a child element, preferably the first one, a link through a parent element with an ID. An example: Code: <div id="parent"> <a href="/">Name</a> <-! start message -> <b>child element text</b> <-! end message -> </div> I want the bold tag to have the link, basically. But through javascript. Dreamweaver is giving me a syntax error, but i dont understand what is wrong. i copied the line from the source code of the demo file included in the download and it it still telling me there is a syntax error. obviously something is wrong bc my slider isnt auto-sliding. so then i tried copying and pasting from the source code of the web page i got the slider from (http://www.ndoherty.biz/demos/coda-slider/2.0/) Dreamweaver then moved the syntax error warning to the line that only contains my closing script tag what am i doing wrong? why am i getting syntax errors? how can i make this thing autoslide? full code available at: http://mydomainsample.com/fire_rebuild Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. i'm working with a javascript on a drupal website, but the saving function seems to work only as soon as i click 2 times on the "save" button. the code that fires the function is: Code: var param ="&usuario="+usuario+"&nivel="+nivel+gano+porc_gano+gasto+porc_gasto+tengo+porc_tengo+debo+ porc_debo+plazo_debo; var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = server_direction +"setMisDatos?callback=respuestaGuardarMisDatos¶m="+encodeURIComponent(param); var h = document.getElementsByTagName("script")[0]; h.parentNode.insertBefore(s, h); //or h.appendChild(s); the chrome console tells me the error is in the last line i copied, but i don't undertand what kind of error it is. using chrome console (specifically the "network" one), i see that it's written in red, status/text "failed", type "undefined" size/content "13 B / 0 B"; when it works it's: status/text "200/OK", type "text/json", size/content "256 B/ 38B". i'm not an expert with this, is there some more information that could be useful? the code fires a netbeans function, that stores data to a postgresql database, so i have like 100 variables that has to be stored when i click on the "save button". Actually before i put parentNode.insertBefore, there used to be appendChild(s), but then i found out this algorithm from google analytics, which seems to be working better than the previous one. Having said that, i can tell you that the GET works after the first time i click perfectly, with some weird things happening, like if i browse another tab for a while, then go back to the page, and click on save, it won't work again (same error). The variables are written like this: Code: var plazo_debo_casa1 = (getValor("plazo_debo_casa1")); var plazo_debo_casa2 = (getValor("plazo_debo_casa2")); var plazo_debo_casa3 = (getValor("plazo_debo_casa3")); var plazo_debo_prestamo1 = (getValor("plazo_debo_prestamo1")); var plazo_debo_prestamo2 = (getValor("plazo_debo_prestamo2")); var plazo_debo_prestamo3 = (getValor("plazo_debo_prestamo3")); var plazo_debo ="&plazo_debo_casa1="+plazo_debo_casa1+"&plazo_debo_casa2="+plazo_debo_casa2+"&plazo_debo_casa3="+plazo_debo_casa3+"&plazo_debo_prestamo1="+plazo_debo_prestamo1+"&plazo_debo_prestamo2="+plazo_debo_prestamo2+"&plazo_debo_prestamo3="+plazo_debo_prestamo3; and then together in the "param" variable. Is it clearer now? i tried to copy document.head.appendChild(s); instead of parentNode.insertBefore(s,h), but it still behaves the same way. Still not any suggestions? This is part of the javascript file loading on my page, and since the function setMisDatos is in netbeans and it works correctly as soon as it's fired (at least, that's what i notice after the first click), i don't think it's worth copying part of it here, right? are there maybe too many variables for the GET method? is there a way to check GET errors? i'm sorry for not being an expert but i would really like some help here. I think the `getJSON` should be taking the JSON URL and returning it as a response - The data file has `Author x3 Body x3 and Title x3`. Once it has this it should map it into the `nodes` and give me three nodes for each section of data. However currently its giving me the `console.log` output that I have below and nothing in my `nodes var` **Console Log:** Code: script.js:7 [Object, Object, Object]0: Object1: Object2: Objectlength: 3__proto__: Array[0] **Code:** Code: $(document).ready(function(){ var url = "assets/js/data.json"; $.getJSON(url).done(function(response) { var nodes = response.map(function(i) { return $('<div>').append( $('<div>', {class: 'title'}).text(i.title), $('<div>', {class: 'author'}).text(i.author), $('<div>', {class: 'body'}).text(i.body) ); console.log(response); }); }); });//Ready function closed Reply With Quote 01-08-2015, 10:56 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts The data file has `Author x3 Body x3 and Title x3`. Literally??? That is, it has something like Code: { Author: "Adam", Author: "Bob", Author: "Carol", Body: "Somethhing...", Body: "something else ...", Body: "more stuff...", Title: "Book one", Title: "Book two", Title: "Book three" } ??? I'm sure that's not what you meant, but what *DID* you mean? Why not simply copy/paste the contents of "data.json" to here? |