tags:

views:

1017

answers:

6

Hello,

I followed this guide to create a new a js to flash communication: http://www.actionscript.org/resources/articles/638/1/Basics-of-using-the-ExternalInterface/Page1.html

So my code looks like:

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}

Now sometimes, my onChange does not load, but currently, firebug displays a "me.onChange is not a function" error and completely stops. I want it to degrade gracefully because this is not the most important feature in my program. I tried typeof but that still gives the same error.

Any suggestions on how to make sure that it exists and then only execute onChange?

Thank you for your time.

UPDATE None of the methods below except try catch one work.

A: 
function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}
MiffTheFox
+2  A: 

Try something like this:

if (typeof(me.onChange) != "undefined") { 
    // safe to use the function
}
Andrew Hare
When not just me.onChange !== undefined...
J-P
+2  A: 

With no conditions

me.onChange=function(){};

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}
Itay Moav
+2  A: 

I like all the answers given so far.

This seems, to me, the usual way to handle this kind of situation:

function js_to_as( str ){
    try {
        me.onChange(str);
    }
    catch(err) {
        // Handle error(s) here
    }
}

I'd love to hear why this is a poor approach.

Adam Bernier
Catch is slow. Augments the scope chain. I'd only use it if I really had to. No reason not to prevent the error in the first place. http://google-code-updates.blogspot.com/2009/06/nicholas-c-zakas-speed-up-your.html
Nosredna
@Nosredna: That's great info. Thank you. Let me know if you think I should delete this answer.
Adam Bernier
No! Don't delete it. It's always good to see what the choices are in a language.
Nosredna
+1  A: 

I would suspect that me is not getting correctly assigned onload.

Moving the get_ID call into the onclick event should take care of it.

Obviously you can further trap as previously mentioned:

function js_to_as( str) {
  var me = get_ID('jsExample');
  if (me && me.onChange) {
    me.onChange(str);
  }
}
wombleton
+1  A: 

I'll go 1 step further to make sure the property is indeed a function

function js_to_as( str ){
     if (me && me.onChange && typeof me.onChange === 'function') {
         me.onChange(str);
     }
}
Alex