简体   繁体   中英

Where to put javascript events in AMD modules?

I am in the process of converting a massive .js file into AMD modules using requirejs

I realise the concept about returning function and such which are much link classes, however, how do I handle events such as:

$('blah blah').onClick( ...

$('blah blah 2').onChange( ...

Do I just create a module that does not return anything? What is the best way to handle these sorts of things?

If you want to be executed just once, at application initialization, just put it in the body of your module and don't return anything:

define([...], function() {
  // All code here will be executed once at initialization.
});

All the body code will be executed once, as long as you import that module. This is a bad idea for jQuery selectors as there is no guarantee that the DOM will be properly loaded when this is evaluated.

If you need to call your code manually, once or more, encapsulate it in an object and you can import and call it when needed:

define([...], function() {
  return {
    registerEvents : function () {
      // All code here will be executed when `module.registerEvents()` is called.
    }
  };
});

This would be the proper way to register DOM events as it gives you more control in regards of when this is evaluated.

Since selecting an element an attaching a handler with a jQuery selector happens over the whole document, it can technically be put anywhere.

I would say it largely depends on how you're organizing your modules.

If you're splitting them up into MV* components, interaction handlers would go in the V* portions (eg a Backbone View).

If you're using some other organizational scheme, generally I'd say put the handlers where they're the most tightly bound. For example, if a module already has a reference to the DOM element you want to bind to, put the handler in with it (and use that specific reference, rather than calling $() to traverse the document, potentially picking up unwanted elements) so that you can unbind the handler at the end of the lifecycle of the element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM