0

I am wanting to know what is the quickest way below to repeat or give this "function" below a name so that I can call it within another function in the same document -> runThisFunction();

Code:

$('body').on("click", ".manufacturer_details_link", function (e) {
                e.preventDefault();

                var self = $(this);
                var id = self.data("id");

                var url = $("#manufacturers_table").data("infourl");

                var data_array = { 
                        id : id 
                    };

                ajaxCall(url, data_array, "rhs_info");

            }); 

2 Answers 2

2

If I understood everything correct:

function bodyOnClick( e, optionalId ) {
    var nodeRef = optionalId ? document.getElementById( optionalId ) : this;

    if( typeof e === 'object' )
        e.preventDefault();

    var self = $(this);
    var id = nodeRef.data("id");

    var url = $("#manufacturers_table").data("infourl");

    var data_array = { 
        id : id 
    };

    ajaxCall(url, data_array, "rhs_info");
}

// ---

$('body').on("click", ".manufacturer_details_link", bodyOnClick );

// ---

bodyOnClick( 'someNodeID' );

But actually, calling bodyOnClick plain doesn't make much sense, since this would not reference any HTMLElement. So it only makes sense if you re-use the method on other event handlers, or explicitly call it like

bodyOnClick.call( someNodeReference );

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Andy, would I pass in an id as nodeRef?
@JessMcKenzie No, it has to be an actual node. I.e. $("#foo")[0]
@JessMcKenzie you could do that, but you would need to re-write the function for that, I edited the function to give you a basic example.
@jAndy I'd suggest not reusing the bind handler, it makes for some unreadable code. I'd split them up into two functions, leaving the bind handler as a lamba function and calling the other function from within that one.
@MarcusEkwall I guess I would agree in general. However, I think the answer here makes some good enough points and examples so ultimately OP and others will realize your note for themselfs :-)
0

You mean like this?

function someFunction(e){
    e.preventDefault();
    var id = $(this).data("id"),
        url = $("#manufacturers_table").data("infourl"),
        data_array = {id: id};
    ajaxCall(url, data_array, "rhs_info");
}
//$('.manufacturer_details_link').click(someFunction);

// changed, per feedback
$('.manufacturer_details_link').on('click', someFunction);

1 Comment

OP is using .on since it's a delegated bind. Don't change it unless you know it will work.

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.