Skip to content

Instantly share code, notes, and snippets.

@caridy
Last active December 20, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caridy/6214570 to your computer and use it in GitHub Desktop.
Save caridy/6214570 to your computer and use it in GitHub Desktop.
requiring optional client side dependencies on common dependencies

What is this?

This is a gist to showcase how to have client affinity modules that are required by common affinity modules without breaking the app when trying to use the common affinity modules on the server side.

Instalation

npm install
node app.js
/*jslint node:true, nomen: true*/
'use strict';
var express = require('express'),
expyui = require('express-yui'),
Locator = require('locator'),
LocatorHandlebars = require('locator-handlebars'),
app = express();
expyui.augment(app); // becoming .extend() soon
app.set('view', app.yui.view());
// serving static yui modules
app.use(expyui['static']());
// creating a page with YUI embeded
app.get('/', expyui.expose(), function (req, res, next) {
// requiring `bar` which works on server and client
req.app.yui.use('bar');
// rendering the page after getting `bar` ready
res.render('demo');
});
// locator initialiation
new Locator({
buildDirectory: 'build'
})
.plug(LocatorHandlebars.yui())
.plug(app.yui.plugin({
registerGroup: true,
registerServerModules: true
}))
.parseBundle(__dirname, {}).then(function (have) {
// listening for traffic only after locator finishes the walking process
app.listen(3000, function () {
console.log("Server listening on port 3000");
});
}, function (e) {
console.log(e);
console.log(e.stack);
});
YUI.add('bar', function (Y, NAME) {
console.log(NAME);
}, '0.1', {
"requires": ["io-base"]
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo - affinity</title>
</head>
<body>
<div id="content">
Loading optional client side affinity module
</div>
<script>{{{state}}}</script>
<script>
app.yui.use('bar', function (Y) {
alert('done');
});
</script>
</body>
</html>
YUI.add('foo', function (Y, NAME) {
console.log(NAME);
// this module is inserted right before "bar" (the trigger) is attached, but only on the client side
}, '0.1', {
"affinity": "client",
"requires": ["node"],
"condition": {
"name": "foo",
"trigger": "bar",
"when": "before"
}
});
{
"name": "demo",
"description": "Overruling YUI.",
"version": "0.0.1",
"private": true,
"main": "app.js",
"dependencies": {
"express": "*",
"express-yui": "*",
"locator": "~0.3.0",
"locator-handlebars": "*",
"yui": "~3.11.0"
}
}
@pdokas
Copy link

pdokas commented Aug 12, 2013

Hey Caridy, what happens if you have a second module -- call it quux -- that also needs foo? Wouldn't the module definition for foo also need to list quux in its trigger?

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