XF 2.0 I'm really confused with scopes in JavaScript...

Jaxel

Well-known member
Below is my JS...
JavaScript:
    EWRatendo.RsvpMenu = XF.Element.newHandler(
    {
        $target: null,
        $parent: null,
      
        init: function()
        {
            this.$target.on('click', '.menu-linkRow', $.proxy(this, 'click'));
        },
      
        click: function(e)
        {
            e.preventDefault();
          
            $target = $(e.currentTarget);
            $parent = $(e.currentTarget).parent();
          
            XF.ajax('POST', $target.attr('href'), {}, function (data)
            {
                alert(this.$target.text);
                alert(this.$parent.text);
            });
        },
    });


I believe there are essentially 3 scopes in the above code... the handler/init scope, the click scope, and the ajax scope.

To assign variables from the click scope to the handler scope, I would need to do this.$target = .....
However, if I do that, then the values are undefined in the ajax scope and are not accessible based on the values set in the click scope.

In order to get the variables working in the ajax scope, I needed to not define this in the click scope; which makes the variables global.
But if the variables are now global; why can I still access them through this? Global variables aren't preferred anyways...

So how do I define variables in the click scope, that I can use in the ajax scope, without having to make them global?
 
Change
JavaScript:
            $target = $(e.currentTarget);
            $parent = $(e.currentTarget).parent();
To use this.$target and this.$parent and then proxy your AJAX complete function:

JavaScript:
                XF.ajax('post', XF.canonicalizeUrl(this.$target.attr('href')), {}, XF.proxy(this, 'handleAjax'));

Then create the handleAjax function:
JavaScript:
handleAjax: function(data)
        {
            if (data.errors || data.exception)
            {
                return;
            }

            alert(this.$target.text);
            alert(this.$parent.text);
        }


Fillip
 
Essentially this in JS probably doesn't work like you might expect coming from PHP. It can vary based on how a function is called, for one. If you have the time and are curious enough, YDKJS is a great free book series that helped to demystify a lot of JS for me. There are books in the series on scope and this.

Per above, you can define a new function and use jQuery's $.proxy() to set the context to that of the handler object when it is called.
 
Last edited:
Top Bottom