Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Forked from davearel/jquery_amd.js
Last active August 29, 2015 13:56
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbranyen/9255362 to your computer and use it in GitHub Desktop.
Save tbranyen/9255362 to your computer and use it in GitHub Desktop.
// Use an AMD package here to gain access to nested internal modules.
require.config({
packages: [{
name: "jquery",
location: "vendor/jquery/src",
main: "index.js"
}]
});
// If we are using AMD, we don't care about core.
define(function(require, exports, module) {
"use strict"
var ajax = require("jquery/ajax");
var data = require("jquery/data");
var req = ajax.get("/modular");
req.then(function() {
// Modules, sucka.
});
exports.ajax = ajax;
exports.data = data;
});
// jquery/html would return a module representing the function.
require(["jquery/html"], function(html) {
html.call(elems, "value");
});
// Want chaining instead, hold onto your seats!!!!
require(["jquery/core", "jquery/html"], function($, html) {
// Attach to core.
$.fn.html = html;
// Now that's what I'm talking about.
$(".some-elems").html("value");
});
@davearel
Copy link

davearel commented Mar 2, 2014

I disagree, only in that I think it's possible for jQuery to have both. However, As I stated before:

Maybe that paradigm doesn't belong in AMD

It may be a little too aggressive for jQuery to migrate away from the current syntax, and I'm not 100% sure if it's in its best interest; chaining is a valuable thing. Regardless, that doesn't mean we can't have chaining and AMD.

My original example was exactly that:

define([

  // jquery core is always required
  'jquery/core',

  // jquery utilities
  'jquery/ajax',
  'jquery/data'

], function(jq, ajax, data) {

  // Using the core module, create a jQuery instance
  // with the required extensions
  var $ = jq.require(ajax, data);

  // The local instance of $ contains the necessary jQuery
  // extensions, but once this module is done executing,
  // "$" no longer exists to other modules.

});

https://gist.github.com/davearel/9254418

Of course, that doesn't describe the actual implementation, but rather the outcome. The point is simply that we extend the core jQuery namespace, with the necessary dependencies, to a LOCAL variable. That way it is only accessible to that particular module.

The require method would return a new instance of jQuery that only contains the core methods and the dependency methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment