0

I need to create custom events in a javascript NameSpace, but i dont know if its possible.

I have a namespace like this:

NAMESPACE = {

   var1 : 'value',
   var2 : 'value',

   initiate : function() {
      console.log('initiate');
   },

   clear : function(arg) {
      console.log('clear');
   }

   fail : function() {
       // Here i need to trigger the error event..
   }

}

That creates events using this method:

var myEvent = new CustomEvent("errorX", {
  data: {
    param: "value"
  }
});

document.dispatchEvent(myEvent);

// In document.ready...
$(document).on('errorX', function(e) {
   console.log(e);
});

This works, but I need to attach the addEventlistener to the document and I would like to attach this to the namespace object, like:

$(NAMESPACE).on('errorX', function(e) {
    console.log(e);
});

It this possible?

0

1 Answer 1

1

You can use the .triggerHandler method:

$(NAMESPACE).on('errorX', function(e) {
    console.log(e);
});

$(NAMESPACE).triggerHandler("errorX");

demo: http://jsfiddle.net/Enq9h/

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

5 Comments

@Zenth you don't need .dispatchEvent at all, jQuery doesn't use it. It uses .triggerHandler/.trigger
I update your example trying to make similar to my code, but dont get the event params.. possible reason?
@Zenth you can pass arguments in the second argument as an array: jsfiddle.net/Enq9h/3 I also recommend .triggerHandler over . trigger because it's optimized for custom events on normal objects.
OK, its possible to do this without jQuery? (Using only jquery in the "$(NAMESPACE).on('errorX..")
@Zenth yes if you make your custom event library or use existing one. But if you are already using jQuery you might as well use it.

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.