Problems With My Function in Javascript - javascript

I'm having problems with some javascript code that I can't seem to figure out. The function I use is
var tagline = new function(){
document.write(
tags[
Math.floor(Math.random()*10)
]
);
};
which calls on an array of 10 strings called "tags" and displays a random entry from that array.
The problem is that for some reason the function executes even when it isn't called, and when I do call it nothing happens. The function just puts the text in the top left corner and does nothing different whether it is or isn't called. This is especially a problem with the styling, because no matter what I do I can't change the position, size, etc. of the text.
(Yes, I'm aware I can do the same thing with
document.getElementById("tag").innerHTML = tags[Math.floor(Math.random()*10)] ;
but I like to write my own functions.)
Thank you for any help you can give!

It's because you use the new keyword. Remove that so it becomes:
var tagline = function(){
By using the new keyword, you are instantiating a new object from the function, which immediately calls it, and your variable then contains the object, not the function, which explains why you can't call it after it first executes.

Related

Weird behavior in xpage/javascript variable assignment

I'm having this weird behavior and I'm not sure if it's me not misunderstanding variables or it's an xpage issue
I have a document with a field called "hours" and it has a value of 8.
Here is my simplified code .
var xHrs = doc.getItemValueDouble('hours');
println (xHrs); // at this point, hours is 8
doc.replaceItemValue('hours', 0);
return xHrs; // returns 0;
Why is xHrs back to 0 when I replace the document value to 0? How do I break the link?
Thanks in advance for the help :)
R.
Chances are that the code is being executed more than once.
Try wrapping the code with ${javascript: rather than #{javascript:
${javascript:
var xHrs = doc.getItemValueDouble('hours');
doc.replaceItemValue('hours', 0);
return xHrs;
}
The code will be executed only once with the preceding $.
I suspect that setting your xHrs variable as you do creates a function expression that returns the value of the 'hours' field. You change the value of the field and the function returns the new value.
I'm not sure about breaking the chain in an efficient manner, but maybe if you create a second variable to hold the xHrs value?

Getting an image in Base64 format as global variable

I am trying to get image in Base64 format outside of
var codedPic;
var purl = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
var codedPic = convertImgToBase64(purl, function(base64Img){ console.log('attempt 1: ' + base64Img); });
console.log('attempt 2: ' + codedPic);
It is getting results of attempt 1 but for attempt 2 it displays undefined. But I need it working too. Can anyone help me please?
Please feel free to amend this jsfiddle: http://jsfiddle.net/s7x0otdc/2/
(in fiddle) after you complete the conversion, you call callback, therefore nothing is stored in codedPic variable.
you can fix it by using return codedPic; instead of using callback
or you can do everything you need in that callback function (because after completing callback function you lose "hers" variables)
i suppose there is some way with global vars.. but just now i don't know how i would do that
EDIT:
New demo to show you how to modularize your code. The encoded picture is available outside of your conversion function (more precisely in your global variable codedPic). But you have to wait for your callback to be triggered to be sure it now has the correct value.
http://jsfiddle.net/s7x0otdc/7/
Well you have several mistakes in your code.
As pointed out by Jimmmy, your function does not return anything, so the assignment var codedPic = convertImgToBase64(purl /* ... */ ); is useless as codedPic will remain undefined.
Time to read How to return the response from an asynchronous call? to understand why you need to use callbacks, and that you have to put any code that depends on a server response inside a callback. Since your conversion function needs to wait for the load event of your image, you will get data into dataURL at an unkown moment in the future. When this moment arrives, JS will trigger your callback and give it that data as argument, as per your conversion function specifies. So only your callback can safely assign your desired data into a global variable, and trigger any action that depend on that data.
Demo: http://jsfiddle.net/s7x0otdc/5/

Maximum call stack size exceeded with Javascript Canvas animation

I have a jsFiddle that I've been messing around with, trying to get my little game to become more organized with classes and such, but when I request an animation frame, passing in the objects (each frame does a few functions with each object), I get a Maximum call stack size error. How can I fix this without abandoning my classes?
The jsFiddle:
http://jsfiddle.net/Blawkbuilder/Q5U3X/109/
the line I suspect to be the culpurit:
window.requestAnimationFrame(draw(p1,p2));
but the line the console links to occurs somewhere in jquery:
} else if ( !rhtml.test( elem ) ) {
Fix? I'm a bit new to javascript.
(If needed, here is the previous, not class based version that still functions how I want this too)
http://jsfiddle.net/Blawkbuilder/9hmca/131/
requestAnimationFrame takes a callback. You are evaluating draw(p1, p2) and passing its return value to requestAnimationFrame. You should change to something like this:
requestAnimationFrame(function() { draw(p1, p2); });
This is similar to setInterval/setTimeout.
requestAnimationFrame takes a callback function with no arguments as a parameter. The reason you're getting a stack overflow is that you're providing the parameter draw(p1, p2) (rather than draw), which actually invokes the draw function, which then makes the same mistake of invoking the draw function ... (and so forth). You're doing it correctly in the second jsFiddle.
To get around this, you need draw to not take any parameters. Alternatively, create a "wrapper" function that doesn't take any parameters, which itself simply invokes draw with the appropriate parameters. The simplest way to do this do something like requestAnimationFrame(function() {draw(p1, p2); }) as the other answer suggests.
By the way, telling you this is metaphorically giving you a fish, rather than teaching you how to fish. To really understand this, you need to understand a bit more about functional programming, which can get a little abstract. In this example, understand that functions are nothing more than objects that have the special property of being "callable" (or "invokable"). requestAnimationFrame is a function whose first parameter, callback, is another function. requestAnimationFrame is expecting that callback is callable, in other words. But you're giving it the result of calling the function, rather than the function itself.
The reason function() {draw(p1, p2);} works is that the function() { ... } syntax constructs an anonymous function -- a function without a name, but still a function that can be invoked.

Does the use of prototyping in javascript have a negative effect on ajax calls and asynchronous code?

If I had the following object and prototyped functionality added on.
function Hello (input){
this.input = input
}
Hello.prototype.ajaxcall = function(id){
$.get("/ajax/method", {parameter:input}, function(data){
$("#"id).html(data);
});
}
Forgive the syntax if not completely correct but what it should be doing is taking in an element id, performing an ajax call and assigning the ajax call result to the innerHTML of the id. Will the fact that the ajaxcall function is shared across all instances of an object cause any problems with regards to what data will be assigned to which id if for example 20 object were all created together and had this function called immediately?
If this is the case, does it make sense to put asyncronous methods inside the object constructor instead?
What would happen if 20 objects would be created and the ajaxcall function would be called? Nothing much. The ajax calls would run asynchronously. When they have finished they are queued so that they run on the main thread when the current running operation on the main thread finished.
So the callback functions run all synchronous in a queue next time there's time for it. Nothing bad can happen here.
I don't understand your question about the constructor. What would that change? If you use your Hello objects they have an instance variable. This is is enclosed in the callback closure . Creating a new function doesn't change the value in another callback function.
If you use the same IDs the content could flash when the text changes and you don't know which callback would be ran last but that's the worst thing that could happen.
There should be no issue. You're calling the function 20 distinct times with 20 different ids.
Conceptually though. I'm not seeing why this is part of your object. The function does not use anything at all from the object itself.
This particular example would work. Your function makes no use of any instance variables, so it doesn't really make sense to declare it that way, but it makes even less sense to move it into the constructor. Still it will work because the id argument will not be shared between calls.
EDIT: So now that you've changed it so that it does use an instance variable you've got the syntax wrong, it needs to be
{parameter : this.input}
But aside from that it will still work. The asynchronous behaviour is not a problem for the code shown.

Using Firebug and jsfiddle.net to test a function

Im a newbie programmer who got the function below from Stoyan Stefanovs object oriented JavaScript Book. He says that if you call next three times, it will output "a" and "b" and then "c". When I tried it in firebug console, it kept giving me "a", so that`s one question (a) i.e. is there something about firebug that would explain my result?
Next, I tried to run it in jsfiddle.net but it won`t output anything. http://jsfiddle.net/mjmitche/SkSMm/
Im sure Im doing something wrong, but what? Please explain if you can. Note, I did next(); and got A, and then I did next(); again and got 'a' and next(); again and got 'a'. In other words, the counter didnt change or didnt remember.
function setup(x) {
var i = 0;
return function () {
return x[i++];
};
}
var next = setup(['a','b','c']);
next();
Here is the jsfiddle link to show it works:
http://jsfiddle.net/ZnZTk/
JsFiddle is not like the console, it doesn't have a window where it will output return values. The result of the code is a web page, that is shown at the lower right.
You can use the alert method to show the values:
alert(next());
http://jsfiddle.net/SkSMm/4/
As you see, calling next three times will actually output the three values in the array. The setup function returns a delegate to the anonumous function that is created in the function. As that anonymous function uses variables outside itself, but which are local to the surrounding function, a closure is created for the function. The closure will contain the i and x variables. As the closure belongs to the delegate, it will survive from one function call to the next, and retain the values of it's variables.
You could do a similar thing just using global variables:
var x = ['a','b','c'];
var i = 0;
function next() {
return x[i++];
}
alert(next());
alert(next());
alert(next());
As the variables are declared outside the function, they will survive between the function calls.
The drawback of using global variables is that one script easily clashes with another if the variables are not given very unique names. If you use a closure, there is no risk of the variables of one script to conflict with variables of another script.
You did it wrong:
And jsfiddle: http://jsfiddle.net/ZHgW2/
Here's a neat demo that takes advantage of an imported say function and relies on a button:
http://jsfiddle.net/entropo/wxTqR/
This is a great way to test your scripts without relying on the log or alerts.
The say function is from jQuery in Action. Excerpt:
Within this function, we employ the services of a small utility function, say() C,
that we use to emit text messages to a dynamically created element on the page
that we’ll call the “console.” This function is declared within the imported support
script file (jqia2.support.js), and will save us the trouble of using annoying and disruptive alerts to indicate when things happen on our page. We’ll be using this handy function in many of the examples throughout the remainder of the book.

Categories