views:

190

answers:

1

I working on adding file uploading to my web application. I'm using an iframe to post my upload. When my php script processes the upload it writes some JavaScript to the iframe. This JavaScript is attempting to attach a function to the parent, this works, but when this function actually gets called it doesn't have the correct scope. Here is the code I'm attaching to the parent window:

parent.window.showPreview = function(coords)
{
    if (parseInt(coords.w) > 0)
    {
        var rx = 200 / coords.w;
        var ry = 250 / coords.h;

        $('#preview').css({
            width: Math.round(rx * 400) + 'px',
            height: Math.round(ry * 533) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    }
}

When this function gets executed I get an error that says $ is not defined. I've tried adding changing the JQuery call to parent.$('#preview').css..., but then it says that parent is undefined. Any ideas?

+1  A: 

Try this:

var p$ = parent.window.$;
parent.window.showPreview = function(coords) {
    if (parseInt(coords.w) > 0)
    {
        var rx = 200 / coords.w;
        var ry = 250 / coords.h;

        p$('#preview').css({
            width: Math.round(rx * 400) + 'px',
            height: Math.round(ry * 533) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    }
}

If you're making a function for the parent window, you probably want it to use the parent window's jQuery instead of the child window's. You'll also need to make sure the parent page has its own copy of jQuery. (If it doesn't, and you're brave, you could try dynamically giving it one!)

edit

Here's how you could do it with a closure instead of the global p$:

parent.window.showPreview = (function(p$) {
  return function(coords) {
    // ... same as above
  };
})(parent.window.$);
Pointy
I tried this, it doesn't seem to be working. p$ is not defined.
Ronald
Well does your parent page have a `<script>` tag to import jQuery? It should.
Pointy
Yep. It does. I can call it successfully too, like so: parent.$("#crop-controls").html(cropcontrols); It's just this function that is having the scoping issue. :\
Ronald
Well if "parent.window.$" is defined, then how can "p$" not be defined? You could do the definition with a closure I guess.
Pointy
Well, I tried the same code in Chrome and it works there. So this looks like a Firefox issue.. hmm...
Ronald
The closure works in Firefox and Chrome. Thanks buddy!
Ronald
Good - that's probably how I'd do it anyway because I hate global variables :-)
Pointy
Do you think that's a Firefox bug? Should I report that issue?
Ronald
Hmm ... I'm not sure it's a bug, but I don't consider myself expert enough to say one way or the other.
Pointy