Use CommonJS Module Definitions with RequireJS
Your client side apps can quickly become unwieldy, but writing definitions that resemble:
define([
'jquery',
'underscore',
'backbone',
'models/SomeModel',
'views/SomeView',
'jquery.tmpl'
], function ($, _, Backbone, SomeModel, SomeView) {
};
can be cumbersome and error prone. In the above example, if I add a new requirement and new argument and I don't notice that jquery.tmpl isn't defined as a parameter, I'm going to get a failure in my app. It's also annoying to copy and paste to other definitions, due to the module and parameter being on different lines.
I much prefer using the CommonJS format, where the code will be as below:
define(function (require, exports, module) {
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
TimerModel = require('models/SomeModel'),
TimerView = require('views/SomeView');
require('jquery.tmpl');
};
This way, we can easily add required modules with or without parameters. It's also extremely simple to copy the definition in part or it's entirety.
Written by Ian Wootten
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside