0

I'm trying to call a variable function name as I've done many times before using similar code from here with

<script type="text/javascript">
    $.fn.toggleHeightAndOpacity = function(show) {
        $(this).stop(true,false).animate({
            opacity: (show)?'show':'hide',
            height: (show)?'show':'hide'
        },
        function(){
            $(this).css('display', (show)?'auto':'none')
        })
    };

...

ws.onmessage = function (evt) {
    var data = JSON.parse(evt.data);
    if(evt.data.type = 'function'){
        var parameters;
        try{
            parameters = JSON.parse(data.parameters);
        }
        catch(e)
        {
            parameters = data.parameters;
        }
        $('#'+data.id)[data.function](parameters)
    }
};

but I keep getting Uncaught TypeError: Property '$.fn.toggleHeightAndOpacity' of object [object Object] is not a function even though the JSON returned from my WebSocket server is {"function":"$.fn.toggleHeightAndOpacity","id":"container","parameters":true,"type":"function"}.

container exists in my html, and jQuery is loaded.

How can this be resolved?

Community
  • 1
  • 1

1 Answers1

2

Objects can be accessed with either dot or bracket notation, so these two are the same

object.key

object['key']

As jQuery selectors and methods are objects, like everything else in javascript, they to can be accessed the same way, so these two are the same

$('#element').fadeIn();

$('#element')['fadeIn']();

That means the plugin can be accessed with these two methods

$('#'+data.id)['toggleHeightAndOpacity'](parameters);

$('#'+data.id).toggleHeightAndOpacity(parameters);

So, if the data returned from the server really is

{"function":"$.fn.toggleHeightAndOpacity", ...

You're really doing

$('#'+data.id)['$.fn.toggleHeightAndOpacity'](parameters)

and that doesn't look right, it should be

$('#'+data.id)['toggleHeightAndOpacity'](parameters)

so change the serverside code to output the function name without $.fn.
Using function as a key looks a little hinky as it's a reserved keyword in javascript, so I would get in the habit of not naming keys or variables function

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thank you so much adeneo! And thank-you for the tip on not using the keyword! Would you mind also posting why I was incorrect? I don't understand why. Thank you so very much in advance! –  Jan 11 '14 at 20:36
  • Absolutely beautiful! Thank-you! –  Jan 11 '14 at 20:40