1

I'm working on a project where a number of different companies are working on the same site.

The main developer have set up an event - let's call it init - which indicates the page is ready for our code to execute.

They're basically calling it like this:

$(window).trigger('init');

For a number of reasons I won't go into here, we prefer to avoid using jQuery in our own code wherever possible. I tried to bind to it like this:

window.addEventListener('init', function (event) {
    alert('hehehehe');
});

But that doesn't seem to work. This works perfectly, though:

$(window).bind('init', function (event) {
    alert('hehehehe');
});

Does jQuery use special event objects by default that you can't bind to with plain JS? Am I just doing something stupid?

1 Answer 1

3

The docs for bind seem to contain the answer:

Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().

There's no native DOM event called 'init':

http://en.wikipedia.org/wiki/DOM_events

Hence "These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler()"

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

4 Comments

Ah, so I can't easily bind to a custom JavaScript event, I guess?
@Cerales: correct. You'd have to implement your own pubsub system and then convince all the other developers to use it. And convince them it's better than using one that someone already built for them, namely jQuery. Good luck with that...
@Domenic - or get them to stop using their custom event system and use the standard DOM event system that doesn't require a 3rd party library and is supported natively by the browser.
Standard DOM event system is inadequate for implementing general-purpose pubsub, which is what your coworkers need for custom events.

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.