1

I have a global jQuery object defined in an external file:

var App = function () {

    function handleTableRowSelection()
    {
        /*
        TRs being generated dynamically via json AJAX call. 
        Select nearest static element then pass in TRs.
        */
        $('table.allow-selection tbody').on('click', 'tr', function(e)
        {
            /*Don't change row class if clicking on a link (HTMLAnchorElement), or any other sub-element*/
            if ((e.target instanceof HTMLTableCellElement) == true)
            {
                var row = $(this);

                row.find('td').each(function()
                {
                    $(this).toggleClass('user-selected');
                });
            }
        });
    }

    return {
        init: function ()
        {
            handleTableRowSelection();
        },

    };
}();

When I call App.init(); in my $(document).ready it works fine (from my master blade template), even though I'm not passing any parameters to handleTableRowSelection.

When I try to call App.handleTableRowSelection('#details', 'table.allow-selection tbody tr') from a sub-template for a single view, I get "undefined is not a function".

I'm calling the init method in my master template like so: App.init();

I thought I'd be able to access the App object (my IDE code-completion finds it), is this not the case?

1 Answer 1

3

App is being set to an IIFE which returns a structure that contains { init: <your function> }. No other functions are being exposed outside the IIFE - that is the whole point of the IIFE when used this way: To provide "private" storage for functions and to export a public interface.

If you want to be able to publicly invoke that function by that name, your last return needs to make it available as a property on the object it's "exporting":

return {
    init: function ()
    {
        handleTableRowSelection();
    },
    handleTableRowSelection: function () {
        handleTableRowSelection();
    }
};
Sign up to request clarification or add additional context in comments.

4 Comments

Would that not call handleTableRowSelection() twice?
No, it wouldn't. You're returning an object with a function which invokes that function, once.
Then how does App.init() (in my master template) run the handle method if it's only returning it?
It doesn't; I assumed you were doing that. As it stands, what you've written would require you to run App.init() to invoke that function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.