Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery custom events data (subscribe and trigger)

I'm trying to figure out, how I can set arguments for custom events. How I can set an argument when I subscribing the event and then add some additional data when i trigger event.

I have a simple JS for testing, but in e parameter of "handle" i see only data of subscribe.

function handle(e) {
    //e.data has only "b"
    alert(e.data);
}

function myObj() {
    this.raise = function () {
            //Trigger
        $(this).trigger("custom", { a: "a" });
    }
}

var inst = new myObj();
//Subscribe
$(inst).bind("custom", { b: "b" }, handle);
inst.raise();

Thank you.

like image 885
Alex Dn Avatar asked Jul 02 '12 14:07

Alex Dn


People also ask

How to trigger an event in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

What is the jQuery method for attaching a custom event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

How do I trigger a click event without clicking?

If you want to trigger click event without clicking a button manually, then you should use the click() method in Javascript. Example : click button on page load dynamically. For that we will create a button with an id my-btn . So that, we can select the button using the getElementById() method.


1 Answers

Parameters supplied to .trigger() are passed as the second parameter of the event handler function.

function handle(e, triggerParam) {
    //e.data has only "b"
    alert(e.data + ' also ' + triggerParam);
}
like image 60
Pointy Avatar answered Oct 12 '22 23:10

Pointy