Call function in variable object using onclick? - javascript

Okay so here is my problem my javascript is so,
var example = {
meep: function() {
alert("This alert or function does not happen using onclick D:");
}
}
Looks fine right? Okay so now when I do this,
<button onclick="example.meep()"></button>
It does not work and returns "Uncaught TypeError: undefined is not a function"
I can also do the function "example.meep()" in console and it works. I've tried it with and without ending parentheses.

try attaching the example to the window. Change
var example = {
...
to
window.example = {
...

Related

How to correctly define (function || function) inside a Javascript object?

This works:
<div id="result"></div>
<script type="text/javascript">
var Base64Encode = window.btoa || CryptoJS.enc.Base64.stringify;
document.getElementById('result').innerHTML = Base64Encode("Please work.");
</script>
However, this:
<div id="result"></div>
<script type="text/javascript">
var Test = {
Base64Encode: window.btoa || CryptoJS.enc.Base64.stringify
};
document.getElementById('result').innerHTML = Test.Base64Encode("Please work.");
</script>
Generates an error of "TypeError: 'btoa' called on an object that does not implement interface Window."
Fiddle:
http://jsfiddle.net/kAGU2/
Why does the first example work but the second one emit that error? What's the correct way to fix this particular error?
Why does the first example work but the second one emit that error?
When the function is called as Base64Encode(), the this context is implicitly set to window. However, when you call it as a method on Test.Base64Encode(), this will refer to Test and btoa grumps about that.
What's the correct way to fix this particular error?
You will need to bind it to the expected context:
Base64Encode = window.btoa
? window.btoa.bind(window)
: CryptoJS.enc.Base64.stringify;
Use .bind():
var Test = {
Base64Encode: function() {
if (window.btoa)
return window.btoa.bind(window);
return CryptoJS.enc.Base64.stringify;
}()
};
You got the error because you invoked the function via that object property reference. When you do that, the value of this is set to a reference to the object involved. The btoa() function doesn't like that (for who knows what reason), but .bind() creates a wrapper function for you that ensures the proper this.
It appears as that btoa function is a member function of Window class. And so it has to be called with this set to window.
In order it to work in your setup you should call it this way:
Test.Base64Encode.call(window,"Please work.");

Attaching a function to the window object not working in IE8

I have a function defined on the window object somewhat like this
window["functionName"] = function(){
// code here
};
Now whenever I need that function I just call
window["functionName"]();
This works well in all browsers except IE8. IE8 throws an error
SCRIPT438: Object doesn't support property or method 'functionName'
I googled for explainations but didnt find any.
EDIT: After a long time debugging I got the cause of the error
Actually the above function definition was inside another function.
function otherFunction(){
window["functionName"] = function(){
// code here
};
// code here
}
When I moved it outside it looked to work fine.
window["functionName"] = function(){
// code here
};
function otherFunction(){
// code here
}
But I still cannot understand why this weird behaviour?

Execute JavaScript from String

So, I want to run this script when button A is clicked. The script is stored in an Object as a string. When button A is clicked, I use eval, like: eval(Object[script]). This works fine, unless I have functions within the script, when I do, it breaks because they are not getting defined. Is there a way to get around this? I tried putting the function definition in a var and putting it at the top of the script. Now, if I simply copy my script to the console, it executes perfectly. Is there a way to execute a script as if it were typed into the console?
FYI: This is a simplification of my problem, I realize there are better ways to do what I describe here.
The best fix is to stop storing code as strings. Use functions instead.
buttonA.script = function() {
do whatever you were doing in your eval
};
// then, instead of `eval(buttonA['script'])`, say...
buttonA.script();
// or, if the name is in a variable...
var foo = 'script'; // for example
buttonA[foo]();
About the only time eval makes sense is when you have code that by its very nature has to be dynamically generated or interpreted. For the vast majority of cases, that is not true. I can only think of a case where it would be true, in fact: the textarea script testing thing mentioned in the comments.
For every other case...
obj = {
first: function() {
function test() { alert('hi'); }
test();
}
};
obj['first']();
// or simply
obj.first();
// and what's more...`test` doesn't escape and trample on stuff.
try { test(); }
catch (ex) { alert("" + ex); } says `test` is not defined
This works:
var oFunc = function (value) {
alert(value)
}
var obj = { code: "oFunc('hello')" }
eval(obj["code"]);
Or am I missing something?
Update
This also works
var obj = { code: "var oFunc = function (value) {alert(value)}; oFunc('hello')" }
eval(obj["code"]);
In your code alert(hi) should be alert("hi")
obj = {
first: 'function test() { alert("hi") } test();'
}
eval(obj["first"]);
DEMO.

Object property initially returns undefined, but upon redefinition returns expected value

I’ve got a JavaScript object built like this:
var Dashboard = {
form: {
action: function(){
return $('#upload_form').attr('action');
}(),
//snip (more functions)
}
}
If I call (using Chrome 17 on WinXP) Dashboard.form.action in the Chrome console after the page loaded (I checked the script and the function is there) the result is undefined but, if I then redefine Dashboard.form.action using the same function:
Dashboard.form.action = function(){
return $('#upload_form').attr('action');
}();
and subsequently call it, it works as expected!
What am I doing wrong? Is this a bug or am I just overthinking it?
Update:
Re your comment below:
actually what I want to do IS assigning the result to the action property...
In the question you said:
If I call...Dashboard.form.action...
which makes it seem like you're expecting action to be a function (you don't "call" non-functions).
If you're expecting it to be a string (the "action" attribute value from #upload_form), then you don't need to use a function at all. But you do need to be sure that you're doing it after the #upload_form element already exists in the DOM.
To do that, either put your script below it in the markup (anywhere below it is fine; just before or just after the closing </body> tag works well), or wrap your script in a ready call.
So your code becomes either this if it's after the #upload_form in the markup:
var Dashboard = {
form : {
action : $('#upload_form').attr('action'),
//snip (more functions)
}
};
...or this if you want to use ready (anything else using Dashboard will have to wait until ready as well):
jQuery(function($) {
var Dashboard = {
form : {
action : $('#upload_form').attr('action'),
//snip (more functions)
}
};
});
Note that in the second case, Dashboard will no longer be a global variable. That's a good thing, but if you need it to be global for some reason, you can export it:
jQuery(function($) {
var Dashboard = {
form : {
action : $('#upload_form').attr('action'),
//snip (more functions)
}
};
// Export the global
window.Dashboard = Dashboard;
});
Just make sure nothing tries to use Dashboard before ready has fired.
Original answer:
You have an extra pair of () on that:
action: function(){return $('#upload_form').attr('action');}()
// here -------^^
By putting them there, you call the function immediately, and assign the result of calling it to the action property. You just want to assign the function itself to the property, so don't put the () at the end to call it:
action: function(){return $('#upload_form').attr('action');}
This is for exactly the same reason you wouldn't use () here (let's assume you have a function called foo) if you want f to refer to foo:
var f = foo;
If you said
var f = foo();
...you'd be calling foo, not referring to it.

Debugging ActionScript in Browser

I am trying to implement following:
How can I start a flash video from javascript?
However I am unable to call method from Javascript. The trace message I wrote within AS file is not able to see while calling file within browser.
How can I test whether my JS function is calling AS method or not?
The FlashBug addon for Firefox lets you see Flash trace outputs in your browser.
here is the code which I am using:
import flash.external.*;
var flashFunction:String =
"jsstopMainVideo"; var
realFunction:Function = stopMainVideo;
function stopMainVideo(){
trace("called from javascript");
//flvPlayer.stop(); }
//stopMainVideo();
var wasSuccessful:Boolean =
ExternalInterface.addCallback(flashFunction,
null, realFunction);
In JS I am doing:
var me = null; function
getID( swfID ){
if(navigator.appName.indexOf("Microsoft")
!= -1){
me = window[swfID];
}else{
me = document[swfID];
} } getID("signupVideoVideo");
me.jsstopMainVideo();
I am getting JS error that function me.jsstopMainVideo() is not a function
The simplest method is to create a javascript function that only has an alert function inside.
try calling it, you either get the pop-up or you don't.
edit:
Alert is a javascript command, but you can call it directly from flash using external interface call.
as:
var call_java:uint;
call_java = ExternalInterface.call('alert','!!!');
or... call the alert from a function
AS:
var call_java:uint;
call_java = ExternalInterface.call('myFunction','!!!');
javascript:
funciton myFunction(val)
{
alert(val);
}
Just check this example http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html , maybe you forgot something

Categories

Resources