user1464139
user1464139

Reputation:

How can I set up a $.fn. function so it gets executed when called?

I have the following code:

    function init() {
        var $contentButtonPanel: JQuery = $('#content-button-panel')
        $contentButtonPanel
            .find('.arbo .toggle, .collapsible-list li:has(ul) > :first-child, .collapsible-list li:has(ul) > :first-child + span')
            .click(function (event) {
                $(this).toggleBranchOpen();
            });
    }

    $.fn.toggleBranchOpen = function () {
        this.each(function () {
            $(this).closest('li').toggleClass('closed');
        });
        return this;
    };

When I debug I can see that the $(this).toggleBranchOpen(); line is reached. However the code does not go inside that function.

Is this a problem with the way that toggleBranchOpen is declared? Note that the only time toggleBranchOpen is used is inside of the init function click event. Is it possible for me to move that code into the init and simplify things?

Upvotes: 0

Views: 50

Answers (2)

Alfero Chingono
Alfero Chingono

Reputation: 2663

Please try this code:

function init() {
    $('#content-button-panel')
        .find('.arbo .toggle, .collapsible-list li:has(ul) > :first-child, .collapsible-list li:has(ul) > :first-child + span')
        .click(function (event) {
            $(this).closest('li').toggleClass('closed');
        });
}

Since you indicated that you don't need the global function, I tried to simplify the code a bit.

Hope that helps.

Upvotes: 1

whitneyit
whitneyit

Reputation: 1226

The declaration is fine. Since you're modifying jQuery's prototype it will be immediately available to all jQuery Objects.

This is the line that is confusing me though,

var $contentButtonPanel: JQuery = $('#content-button-panel')

I would assume this is just cause you are copying and pasting from a larger file. My only advice as to help identify the problem would be to put some debug information inside this loop;

this.each(function () {
    $(this).closest('li').toggleClass('closed');
});

Other than that, is it possible that you're selector isn't finding any li elements?

Upvotes: 0

Related Questions