Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

fixed conflicts

  • Loading branch information...
commit 76b9821bd7e2a2a7d733e947ba1838ebcc090755 2 parents 305de2c + 57d02a4
@tmpvar authored
View
45 README.md
@@ -105,21 +105,18 @@ Using JSDOM, we can easily create a DOM, load some libraries and read a file. Le
var fs = require('fs'),
jsdom = require('jsdom');
- jsdom.env({
- code: [
- '/../lib/jquery.js',
- require('weld').filepath
- ],
- html: '/../files/contexts.html'
- },
- function(errors, window) {
+ jsdom.env(
+ './test.html',
+ ['./jquery.js', './weld.js'],
+ function(errors, window) {
- var data = [{ name: 'hij1nx', title : 'code slayer' },
- { name: 'tmpvar', title : 'code pimp' }];
+ var data = [{ name: 'hij1nx', title : 'code slayer' },
+ { name: 'tmpvar', title : 'code pimp' }];
- window.weld(window.$('.contact')[0], data);
+ window.weld(window.$('.contact')[0], data);
- });
+ }
+ );
Here is the corresponding markup that our script above will load...
@@ -227,7 +224,7 @@ Weld will automatically import the nodes into the proper document (dest.html)...
jsdom.env(path.join(__dirname, 'files', 'source.html'), function(serrs, sw) {
var sources = sw.document.getElementsByTagName("span");
- jsdom.env(path.join(__dirname, 'files', 'dest.html'),[jqpath, wpath], function(errors, window) {
+ jsdom.env(path.join(__dirname, 'files', 'dest.html'), [jqpath, wpath], function(errors, window) {
var $ = window.jQuery;
@@ -314,14 +311,22 @@ Debugging recursive data can be a real pain. With the `debug` option, you can se
};
-## Credits
-developed by [hij1nx][2] and [tmpvar][3]
-
If you want to learn more about JSDOM, go [here][1] it's an awesome project.
## Version
-0.2.0
+0.2.1
+
+## Licence
+
+(The MIT License)
+
+Copyright (c) 2011 hij1nx <http://www.twitter.com/hij1nx>, tmpvar <http://www.twitter.com/tmpvar>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
-[1]: https://github.com/tmpvar/jsdom
-[2]: http://twitter.com/hij1nx
-[3]: http://twitter.com/tmpvar
+[1]: https://github.com/tmpvar/jsdom
View
115 demo/public/css/index.css
@@ -1,115 +0,0 @@
-/* HTML5 ✰ Boilerplate */
-
-html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
-small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
-article, aside, canvas, details, figcaption, figure, footer, header, hgroup,
-menu, nav, section, summary, time, mark, audio, video {
- margin:0;
- padding:0;
- border:0;
- outline:0;
- font-size:100%;
- vertical-align:baseline;
- background:transparent;
-}
-article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
- display:block;
-}
-nav ul { list-style:none; }
-blockquote, q { quotes:none; }
-blockquote:before, blockquote:after,
-q:before, q:after { content:''; content:none; }
-a { margin:0; padding:0; font-size:100%; vertical-align:baseline; background:transparent; }
-ins { background-color:#ff9; color:#000; text-decoration:none; }
-mark { background-color:#ff9; color:#000; font-style:italic; font-weight:bold; }
-del { text-decoration: line-through; }
-abbr[title], dfn[title] { border-bottom:1px dotted; cursor:help; }
-table { border-collapse:collapse; border-spacing:0; }
-hr { display:block; height:1px; border:0; border-top:1px solid #ccc; margin:1em 0; padding:0; }
-input, select { vertical-align:middle; }
-
-
-body { font:13px/1.231 sans-serif; *font-size:small; }
-select, input, textarea, button { font:99% sans-serif; }
-pre, code, kbd, samp { font-family: monospace, sans-serif; }
-
-body, select, input, textarea { color: #444; }
-h1,h2,h3,h4,h5,h6 { font-weight: bold; }
-html { overflow-y: scroll; }
-
-a:hover, a:active { outline: none; }
-a, a:active, a:visited { color: #607890; }
-a:hover { color: #036; }
-
-ul, ol { margin-left: 1.8em; }
-ol { list-style-type: decimal; }
-
-nav ul, nav li { margin: 0; }
-small { font-size: 85%; }
-strong, th { font-weight: bold; }
-td, td img { vertical-align: top; }
-sub { vertical-align: sub; font-size: smaller; }
-sup { vertical-align: super; font-size: smaller; }
-pre { padding: 15px; white-space: pre; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word; }
-textarea { overflow: auto; }
-.ie6 legend, .ie7 legend { margin-left: -7px; }
-input[type="radio"] { vertical-align: text-bottom; }
-input[type="checkbox"] { vertical-align: bottom; }
-.ie7 input[type="checkbox"] { vertical-align: baseline; }
-.ie6 input { vertical-align: text-bottom; }
-label, input[type=button], input[type=submit], button { cursor: pointer; }
-button, input, select, textarea { margin: 0; }
-input:valid, textarea:valid { }
-input:invalid, textarea:invalid { border-radius: 1px; -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; box-shadow: 0px 0px 5px red; }
-.no-boxshadow input:invalid,
-.no-boxshadow textarea:invalid { background-color: #f0dddd; }
-
-::-moz-selection{ background: #FF5E99; color:#fff; text-shadow: none; }
-::selection { background:#FF5E99; color:#fff; text-shadow: none; }
-a:link { -webkit-tap-highlight-color: #FF5E99; }
-
-button { width: auto; overflow: visible; }
-.ie7 img { -ms-interpolation-mode: bicubic; }
-
-.ir { display: block; text-indent: -999em; overflow: hidden; background-repeat: no-repeat; text-align: left; direction: ltr; }
-.hidden { display: none; visibility: hidden; }
-.visuallyhidden { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); }
-.invisible { visibility: hidden; }
-.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; visibility: hidden; }
-.clearfix:after { clear: both; }
-.clearfix { zoom: 1; }
-
-body {
- background-color: #f8f8f8;
-}
-
-@media all and (orientation:portrait) {
-
-}
-
-@media all and (orientation:landscape) {
-
-}
-
-@media screen and (max-device-width: 480px) {
-
-
- /* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */
-}
-
-@media print {
- * { background: transparent !important; color: #444 !important; text-shadow: none !important; }
- a, a:visited { color: #444 !important; text-decoration: underline; }
- a:after { content: " (" attr(href) ")"; }
- abbr:after { content: " (" attr(title) ")"; }
- .ir a:after { content: ""; }
- pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
- thead { display: table-header-group; }
- tr, img { page-break-inside: avoid; }
- @page { margin: 0.5cm; }
- p, h2, h3 { orphans: 3; widows: 3; }
- h2, h3{ page-break-after: avoid; }
-}
-
View
BIN  demo/public/img/weld.png
Deleted file not rendered
View
28 demo/public/index.html
@@ -1,28 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- </head>
- <body>
-
- <div id="accordion">
- <div class="templateRow">
- <h3><a href="#" class="shortName"></a></h3>
- <div class="content"></div>
- </div>
- </div>
-
- <ul class='contacts'>
- <li class='contact'>
- <span class='name'>My Name</span>
- <p class='title'>Leet Developer</p>
- </li>
- </ul>
- <script src="js/weld.js" type="text/javascript" charset="utf-8"></script>
- <script src="js/index.js" type="text/javascript" charset="utf-8"></script>
- <script type="text/javascript" charset="utf-8">
- data.games = [{shortName:'some name', content:'some content'},{shortName:'some name', content:'some content'}]
-
- weld(document.querySelector('.templateRow'), data.games);
- </script>
- </body>
-</html>
View
6 demo/public/js/index.js
@@ -1,6 +0,0 @@
-
- var data = [{ name: 'hij1nx', title : 'code slayer' },
- { name: 'tmpvar', title : 'code pimp' }];
-
- window.weld(document.querySelector('.contact'), data);
-
View
8,176 demo/public/js/jquery.js
0 additions, 8,176 deletions not shown
View
382 demo/public/js/weld.js
@@ -1,382 +0,0 @@
-
-;(function(window) {
-
- /* Returns an array of all own enumerable properties found upon a given object,
- * in the same order as that provided by a for-in loop (the difference being that
- * a for-in loop enumerates properties in the prototype chain as well).
- */
-
- if(!Object.keys) {
- Object.keys = function(o){
- var ret=[],p;
- for(p in o) {
- if(Object.prototype.hasOwnProperty.call(o,p)) {
- ret.push(p);
- }
- }
- return ret;
- };
- }
-
- /* Since weld runs browser/server, ensure there is a console implementation.
- */
-
- window.console || (console = { log: function(){} });
- var color = { gray: '\033[37m', darkgray: '\033[40;30m', red: '\033[31m', green: '\033[32m', yellow: '\033[33m',
- lightblue: '\033[1;34m', cyan: '\033[36m', white: '\033[1;37m' };
-
- /* Weld!
- * @param {HTMLElement} DOMTarget
- * The target html node that will be used as the subject of data binding.
- * @param {Object|Array} data
- * The data that will be used.
- * @param {Object} pconfig
- * The configuration object.
- */
- window.weld = function(DOMTarget, data, pconfig) {
-
- var
-
- /*
- * Configuration Object.
- * @member {Object}
- * Contains an explicit mapping of data-keys to element name/id/classes
- * @member {Boolean}
- * Determines if debugging will be enabled.
- * @method {Boolean|Function}
- * Determines the method of insertion, can be a functon or false.
- */
-
- config = {
- alias : {},
- debug : false,
- insert: false // Default to append
- },
-
- /* The current depth of the traversal, used for debugging.
- */
-
- depth = 0,
-
- /* Generates padding used for indenting debugger statements.
- */
-
- pad = function() {
- var l = depth, ret = '';
- while(l--) {
- ret += '';
- }
- return ret;
- },
-
- /* Debugger statement, terse, accepts any number of arguments
- * that are passed to a console.log statement.
- */
-
- d = function() {
- if (config.debug) {
- var args = Array.prototype.slice.call(arguments);
-
- // This is done because on the browser you cannot call console.log.apply
- console.log(pad(), args.join(' '));
- }
- },
-
- colorize = function(val) {
- var sval = val+'', u='undefined';
- if(navigator.userAgent.toLowerCase().indexOf('node.js') !== -1) {
- if(sval === 'false' || sval === 'null' || sval === '' || sval === u || typeof val === u || val === false) {
- if(sval === '') { sval = '(empty string)' };
- return color.red + sval + color.gray;
- }
- else {
- return color.yellow + sval + color.gray;
- }
- }
- },
-
- /* An interface to the interal operations, implements common
- * debugging output based on a standard set of parameters.
- *
- * @param {Function} operation
- * The function to call in "debug mode"
- */
-
- debuggable = function(name, operation) {
- var label = name.toUpperCase();
- // All of the ops have the same signature, so this is sane.
- return function(parent, element, key, value) {
- console.log(pad(),
- (color.gray + '' + label + ' -'),
- 'parent:', colorize(parent) + ',',
- 'element:', colorize(element) + ',',
- 'key:', colorize(key) + ',',
- 'value:', colorize(value));
- depth+=1;
-
-
- if (operation) {
-
- var res = operation(parent, element, key, value);
- depth-=1;
- console.log(pad(), '' + element + '' + (res !== false ? color.green + '' + color.gray : ''));
- return res;
- }
-
- if (config.debug) {
- depth-=1;
- d('○ OPERATION NOT FOUND: ', label);
- }
- };
- },
- ops = {
- siblings : function(parent, element, key, value) {
- var remove = [],
- sibling,
- classes,
- cc,
- match,
- siblings = parent.children;
- cs = siblings.length; // Current Sibling
- element.weld = {
- parent : parent,
- classes : element.className.split(' ')
- };
-
- // Find all siblings that match the exact classes that exist in the originally
- // matched element node
- while (cs--) {
- sibling = siblings[cs];
-
- if (sibling === element) {
- // If this is not the last item in the list, store where new items should be inserted
- if (cs < siblings.length) {
- element.weld.insertBefore = siblings[cs+1];
- }
-
- // remove the element here because siblings is a live list.
- // which means, if you remove it before hand, the length will mismatch and cause problems
- d('○ REMOVE - element:', colorize(element), 'class:', colorize(element.className), 'id:', colorize(element.id));
-
- parent.removeChild(element);
-
- // Check for the same class
- } else {
- classes = sibling.className.split(' ');
- cc = classes.length;
- match = true;
- while (cc--) {
- // TODO: optimize
- if (element.weld.classes.indexOf(classes[cc]) < 0) {
- match = false;
- break;
- }
- }
-
- // This element matched, you win a prize! DIE.
- if (match) {
- d('○ REMOVE - element:', colorize(sibling), 'class:', colorize(sibling.className), 'id:', colorize(sibling.id));
- parent.removeChild(sibling);
- }
- }
- }
- },
- traverse : function(parent, element, key, value) {
- // LEAF
- if (typeof value === 'string' || (value && value.nodeType)) {
- ops.set(parent, element, key, value);
- // Object / Array-like
- } else {
- var
- target,
- i,
- keys, l,
- array = (value.length && value[0]),
- template = element,
- templateParent = element.parentNode;
-
- if (array && templateParent) {
- ops.siblings(templateParent, template, key, value);
- } else if (array) {
- templateParent = template.weld.parent;
- }
-
- if (array) {
- l = value.length;
- } else if (typeof value === 'object') {
- keys = Object.keys(value);
- l = keys.length;
- }
-
- for (i=0; i<l; i++) {
- key = (keys) ? keys[i] : i;
-
- if (array) {
-
- d('○ CLONE - element:', colorize(element), 'class:', colorize(element.className), 'id:', colorize(element.id));
- target = element.cloneNode(true);
- target.weld = {};
- if (element.weld) {
- for (var weldParam in element.weld) {
- if (element.weld.hasOwnProperty(weldParam)) {
- target.weld[weldParam] = element.weld[weldParam];
- }
- }
- }
- ops.traverse(templateParent, target, key, value[key]);
- ops.insert(templateParent, target);
-
- } else {
- target = ops.match(templateParent, element, key, value[key]);
- if (target) {
- ops.traverse(templateParent, target, key, value[key]);
- }
- }
- }
- }
- },
- insert : function(parent, element) {
- if (element.weld && element.weld.insertBefore) {
- parent.insertBefore(element, element.weld.insertBefore);
- } else {
- parent.appendChild(element);
- }
- },
- elementType : function(parent, element, key, value) {
- if (element) {
- var nodeName = element.nodeName,
- input = /input|select|textarea|option|button/i,
- image = /img/i;
-
- if (typeof nodeName === "string") {
- if (input.test(nodeName)) {
- return 'input';
- }
-
- if (image.test(nodeName)) {
- return 'image';
- }
- }
- }
- },
- map : false, // this is a user-defined operation
- set : function(parent, element, key, value) {
-
- if(config.map && ops.map(parent, element, key, value) === false) {
- return false;
- }
-
- if(config.debug) {
- d('○ SET: value is', value.tagName);
- }
-
- var type = ops.elementType(parent, element, key, value), res = false;
-
- if (value && value.nodeType) { // imports.
-
- if (element.ownerDocument !== value.ownerDocument) {
- value = element.ownerDocument.importNode(value, true);
- } else if (value.parentNode) {
- value.parentNode.removeChild(value);
- }
-
- while (element.firstChild) { // clean first.
- element.removeChild(element.firstChild);
- }
-
- element.appendChild(value);
- res = true;
- }
- else if (type === 'input') { // special cases.
- element.setAttribute('value', value);
- res = true;
- }
- else if (type === 'image') {
- element.setAttribute('src', value);
- res = true;
- }
- else { // simple text assignment.
- // clean first.
- while (element.firstChild) {
- element.removeChild(element.firstChild);
- }
- element.appendChild(document.createTextNode(value)); // Create a new text node with the new value
- res = true;
- }
- return res;
- },
- match : function(parent, element, key, value) {
-
- if(typeof config.alias[key] !== 'undefined') {
- if(typeof config.alias[key] === 'function') {
- key = config.alias[key](parent, element, key, value) || key;
- }
- else if(config.alias[key] === false) {
- return false;
- }
- else {
- key = config.alias[key];
- }
- }
-
- // Alias can be a node, for explicit binding.
- // Alias can also be a method that returns a string or DOMElement
- if (key && key.nodeType) {
- return key;
- }
-
- if(element) {
- if(element.querySelectorAll) {
- selector = ['.' + key, '#' + key, '[name="' + key + '"]'].join(',');
- return element.querySelectorAll(selector)[0];
- }
- else {
- var els = element.getElementsByTagName('*'), l = els.length, e, i;
- // find the _first_ best match
- for (i=0; i<l; i++) {
- e = els[i];
- if(e.id === key || e.name === key || e.className.split(' ').indexOf(key) > -1) {
- return e;
- }
- }
- }
- }
- }
- },
- parent = DOMTarget.parentNode,
- opKeys = Object.keys(ops),
- currentOpKey = opKeys.length,
- currentOp;
-
- // Merge the user configuration over the existing config
- if(pconfig) {
- for(var p in pconfig) {
- if (pconfig.hasOwnProperty(p)) {
- config[p] = pconfig[p];
- }
- }
- }
-
- // Allow the caller to overwrite the internals of weld
- while(currentOpKey--) {
- currentOp = opKeys[currentOpKey];
- var fn = (config[currentOp]) ?
- config[currentOp] :
- ops[currentOp];
-
- if (config.debug) {
- fn = debuggable(currentOp, fn);
- }
-
- ops[currentOp] = fn;
- }
-
- // Kick it off
- ops.traverse(null, DOMTarget, null, data);
-
- if (config.debug) {
- console.log(parent.innerHTML);
- }
- };
-
-})(window);
View
108 demo/server.js
@@ -1,108 +0,0 @@
-
-var sys = require('sys'),
- http = require('http'),
- url = require('url'),
- journey = require('journey'),
- static = require('node-static'),
-
- wpath = require('weld').filepath,
- jsdom = require('jsdom');
-
-(function (port) {
-
- var router,
- server,
- files = new (static.Server)('./public'),
- data = {
- person : [
- {
- name : 'John',
- job : [
- 'guru', 'monkey', 'tester'
- ]
- },
- {
- name : 'Bob',
- job : [
- 'supervise', 'yell'
- ]
- }
- ]
- };
-
- router = function () {
-
- return new (journey.Router)(function (map) {
-
- map.root.bind(function (response) {
- response.send(200, ctypes.json, { message: 'No resource.' });
- });
-
- map.path('/people', function () { // some fake data base calls...
-
- this.get('all').bind(function (response) {
-
- jsdom.env({
-
- scripts: [jqpath, wpath],
- html: path.join(__dirname, 'files', 'singular.html')
-
- },
- function(errors, window) {
-
- var $ = window.jQuery;
- window.weld($('#singular')[0], data);
-
- });
-
- });
-
- this.get('first').bind(function (response) {
-
- jsdom.env({
-
- scripts: [jqpath, wpath],
- html: path.join(__dirname, 'files', 'singular.html')
-
- },
- function(errors, window) {
-
- var $ = window.jQuery;
- window.weld($('#singular')[0], data);
-
- });
-
- });
-
- });
- });
- };
-
- server = http.createServer(function (req, res) {
-
- var body = '';
-
- // Append the chunk to body
- req.addListener('data', function (chunk) {
- body += chunk;
- });
-
- req.addListener('end', function () {
- var uri = url.parse(req.url);
- if (uri.pathname.slice(1).split('/')[0] !== 'people') {
- sys.puts(uri.pathname)
- files.serve(req, res);
- }
- else {
- router().handle(req, body, function (result) {
- res.writeHead(result.status, result.headers);
- res.end(result.body);
- });
- }
- });
- });
-
- if (port) server.listen(port);
- console.log("Demo is running on port "+port);
-
-})(8124);
View
BIN  documentation-assets/github-header.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
227 lib/weld.js
@@ -1,8 +1,4 @@
;(function(exports) {
-
- /* Since weld runs browser/server, ensure there is a console implementation.
- */
-
// shim out Object.keys
// ES5 15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
@@ -52,102 +48,107 @@
}
+ // Start: DEBUGGING
+ // ----------------
+
+ /* Since weld runs browser/server, ensure there is a console implementation.
+ */
+
var logger = (typeof console === 'undefined') ? { log : function(){} } : console;
var nodejs = false;
- // feature test for colorized output
- if (typeof require !== 'undefined') {
+ if (typeof require !== 'undefined' && !exports.define) {
var tty = require('tty');
- if (tty.isatty && tty.isatty(0)) {
- // if this is still a browser, they are trying really hard.
+ if (tty.isatty && tty.isatty(0)) {
nodejs = true;
}
}
+
+ var color = {
+ gray: '\033[37m',
+ darkgray: '\033[40;30m',
+ red: '\033[31m',
+ green: '\033[32m',
+ yellow: '\033[33m',
+ lightblue: '\033[1;34m',
+ cyan: '\033[36m',
+ white: '\033[1;37m'
+ };
+
+ var inputRegex = /input|select|textarea|option|button/i;
+ var imageRegex = /img/i;
+ var depth = 0; // The current depth of the traversal, used for debugging.
+ var successIndicator = nodejs ? (color.green + '' + color.gray) : ' Success';
+ var failureIndicator = nodejs ? (color.red + '' + color.gray) : ' Fail';
-
- var color = { gray: '\033[37m', darkgray: '\033[40;30m', red: '\033[31m', green: '\033[32m', yellow: '\033[33m',
- lightblue: '\033[1;34m', cyan: '\033[36m', white: '\033[1;37m' },
- inputRegex = /input|select|option|button/i,
- imageRegex = /img/i,
- depth = 0, // The current depth of the traversal, used for debugging.
- successIndicator = nodejs ? (color.green + '' + color.gray) : ' Success',
- failureIndicator = nodejs ? (color.red + '' + color.gray) : ' Fail',
- debuggable = function debuggable(name, operation) {
- var label = name.toUpperCase();
- // All of the ops have the same signature, so this is sane.
- return function(parent, element, key, value) {
- var elementStr = 'null';
- if (element) {
- elementStr = element.tagName;
- elementStr += (!!element.id) ? '#' + element.id : '';
- elementStr += (!!element.className) ? "." + element.className : '';
- elementStr += (!!element.hasAttribute('name')) ? '[name="' + element.getAttribute('name') + '"]' : '';
- }
+ var debuggable = function debuggable(name, operation) {
+
+ var label = name.toUpperCase();
+
+ // All of the ops have the same signature, so this is sane.
+ return function(parent, element, key, value) {
+ logger.log(
+ pad(),
+ ((nodejs ? (color.gray + '') : '+ ') + label + ' -'),
+ 'parent:', colorize(parent) + ',',
+ 'element:', colorize(element) + ',',
+ 'key:', colorize(key) + ',',
+ 'value:', colorize(value)
+ );
- var parentStr = 'null'
- if (parent) {
- parentStr = parent.tagName || parent;
- parentStr += (!!parent.id) ? '#' + parent.id : '';
- parentStr += (!!parent.className) ? "." + parent.className : '';
- }
+ depth+=1;
- logger.log(pad(),
- ((nodejs ? (color.gray + '') : '+ ') + label + ' -'),
- 'parent:', colorize(parentStr) + ',',
- 'element:', colorize(elementStr) + ',',
- 'key:', '' + colorize(key) + ',',
- 'value:', colorize(value));
- depth+=1;
+ if (operation) {
+ var res = operation(parent, element, key, value);
+ depth-=1;
+ logger.log(pad(), (nodejs ? '' : '+ ') + element + '' + (res !== false ? successIndicator : failureIndicator));
+ return res;
+ }
+ depth-=1;
+ d('- OPERATION NOT FOUND: ', label);
+ };
+ };
- if (operation) {
+ /* Generates padding used for indenting debugger statements.
+ */
- var res = operation(parent, element, key, value);
- depth-=1;
+ var pad = function pad() {
+ var l = depth, ret = '';
+ while(l--) {
+ ret += nodejs ? '' : ' | ';
+ }
+ return ret;
+ };
- logger.log(pad(), (nodejs ? '' : '+ ') + elementStr + '' + (res !== false ? successIndicator : failureIndicator));
- return res;
- }
+ /* Debugger statement, terse, accepts any number of arguments
+ * that are passed to a logger.log statement.
+ */
- depth-=1;
- d('- OPERATION NOT FOUND: ', label);
- };
- },
- /* Generates padding used for indenting debugger statements.
- */
+ var d = function d() {
+ var args = Array.prototype.slice.call(arguments);
- pad = function pad() {
- var l = depth, ret = '';
- while(l--) {
- ret += nodejs ? '' : ' | ';
- }
- return ret;
- },
+ // This is done because on the browser you cannot call console.log.apply
+ logger.log(pad(), args.join(' '));
+ };
- /* Debugger statement, terse, accepts any number of arguments
- * that are passed to a logger.log statement.
- */
+ var colorize = function colorize(val) {
+ var sval = val+'', u='undefined';
+ if(nodejs) {
+ if(sval === 'false' || sval === 'null' || sval === '' || sval === u || typeof val === u || val === false) {
+ if(sval === '') { sval = '(empty string)' };
+ return color.red + sval + color.gray;
+ }
+ else {
+ return color.yellow + sval + color.gray;
+ }
+ }
+ return sval;
+ };
- d = function d() {
- var args = Array.prototype.slice.call(arguments);
+ // End: DEBUGGING
+ // --------------
- // This is done because on the browser you cannot call console.log.apply
- logger.log(pad(), args.join(' '));
- },
-
- colorize = function colorize(val) {
- var sval = val+'', u='undefined';
- if(nodejs) {
- if(sval === 'false' || sval === 'null' || sval === '' || sval === u || typeof val === u || val === false) {
- if(sval === '') { sval = '(empty string)' };
- return color.red + sval + color.gray;
- }
- else {
- return color.yellow + sval + color.gray;
- }
- }
- return sval;
- };
/* Weld!
* @param {HTMLElement} DOMTarget
@@ -158,9 +159,10 @@
* The configuration object.
*/
exports.weld = function weld(DOMTarget, data, pconfig) {
-
- var
+ var parent = DOMTarget.parentNode;
+ var currentOpKey, p, fn, debug;
+
/*
* Configuration Object.
* @member {Object}
@@ -171,11 +173,22 @@
* Determines the method of insertion, can be a functon or false.
*/
- config = {
+ var config = {
alias : {},
debug : false,
insert: false // Default to append
- },
+ };
+
+ // Merge the user configuration over the existing config
+ if(pconfig) {
+ for(p in pconfig) {
+ if (pconfig.hasOwnProperty(p)) {
+ config[p] = pconfig[p];
+ }
+ }
+ }
+
+ debug = config.debug;
/* An interface to the interal operations, implements common
* debugging output based on a standard set of parameters.
@@ -184,7 +197,7 @@
* The function to call in "debug mode"
*/
- ops = {
+ var ops = {
siblings : function siblings(parent, element, key, value) {
var remove = [],
sibling,
@@ -241,16 +254,17 @@
}
},
traverse : function traverse(parent, element, key, value) {
- var
- type,
- target,
- i,
- keys, l,
- obj,
- template = element,
- templateParent = element.parentNode;
+
+ var type, target, i, keys, l, obj;
+ var template = element;
+ var templateParent = element.parentNode;
// LEAF
+
+ if(~({}).toString.call(value).indexOf('Date')) {
+ value = value.toString();
+ }
+
if (value.nodeType || typeof value !== 'object') {
ops.set(parent, element, key, value);
@@ -406,23 +420,8 @@
}
}
}
- },
- parent = DOMTarget.parentNode,
- currentOpKey,
- p,
- fn,
- debug;
-
- // Merge the user configuration over the existing config
- if(pconfig) {
- for(p in pconfig) {
- if (pconfig.hasOwnProperty(p)) {
- config[p] = pconfig[p];
- }
- }
- }
+ };
- debug = config.debug;
// Allow the caller to overwrite the internals of weld
for (currentOpKey in ops) {
@@ -446,4 +445,10 @@
}
};
-})((typeof exports === "undefined") ? window : exports);
+ if (typeof exports.define !== "undefined" && exports.define.amd) {
+ define('weld',[], function() {return window.weld });
+ }
+
+})((typeof exports === "undefined") ? window : exports);
+
+
View
1  lib/weld.min.js
@@ -0,0 +1 @@
+(function(i){var o=(typeof console==="undefined")?{log:function(){}}:console;var a=false;if(typeof require!=="undefined"){var m=require("tty");if(m.isatty&&m.isatty(0)){a=true}}var h={gray:"\033[37m",darkgray:"\033[40;30m",red:"\033[31m",green:"\033[32m",yellow:"\033[33m",lightblue:"\033[1;34m",cyan:"\033[36m",white:"\033[1;37m"},c=/input|select|textarea|option|button/i,g=/img/i,l=0,f=a?(h.green+" ✓"+h.gray):" Success",k=a?(h.red+" ✗"+h.gray):" Fail",j=function j(r,d){var q=r.toUpperCase();return function(v,u,t,w){o.log(e(),((a?(h.gray+"┌ "):"+ ")+q+" -"),"parent:",b(v)+",","element:",b(u)+",","key:",b(t)+",","value:",b(w));l+=1;if(d){var s=d(v,u,t,w);l-=1;o.log(e(),(a?"└ ":"+ ")+u+""+(s!==false?f:k));return s}l-=1;n("- OPERATION NOT FOUND: ",q)}},e=function e(){var d=l,q="";while(d--){q+=a?" │ ":" | "}return q},n=function n(){var d=Array.prototype.slice.call(arguments);o.log(e(),d.join(" "))},b=function b(r){var q=r+"",d="undefined";if(a){if(q==="false"||q==="null"||q===""||q===d||typeof r===d||r===false){if(q===""){q="(empty string)"}return h.red+q+h.gray}else{return h.yellow+q+h.gray}}return q};i.weld=function p(y,u,D){var t={alias:{},debug:false,insert:false},s={siblings:function A(L,G,N,K){var H=[],M,F,E,I,J=L.children;cs=J.length;G.weld={parent:L,classes:G.className.split(" ")};while(cs--){M=J[cs];if(M===G){if(cs<J.length){G.weld.insertBefore=J[cs+1]}if(d){n("- REMOVE - element:",b(G),"class:",b(G.className),"id:",b(G.id))}L.removeChild(G)}else{F=M.className.split(" ");E=F.length;I=true;while(E--){if(G.weld.classes.indexOf(F[E])<0){I=false;break}}if(I){if(d){n("- REMOVE - element:",b(M),"class:",b(M.className),"id:",b(M.id))}L.removeChild(M)}}}},traverse:function w(O,G,Q,N){var L,K,H,S,E,F,P=G,R=G.parentNode;if(N.nodeType||typeof N!=="object"){s.set(O,G,Q,N)}else{if(N.length&&N[0]){if(R){s.siblings(R,P,Q,N)}else{if(P.weld&&P.weld.parent){R=P.weld.parent}}E=N.length;for(H=0;H<E;H++){if(d){n("- CLONE - element:",b(G),"class:",b(G.className),"id:",b(G.id))}K=G.cloneNode(true);K.weld={};if(G.weld){if(Object.keys){var S=Object.keys(G.weld),M=S.length,I;while(M--){I=S[M];K.weld[I]=G.weld[I]}}else{for(var I in G.weld){if(G.weld.hasOwnProperty(I)){K.weld[I]=G.weld[I]}}}}s.traverse(R,K,H,N[H]);s.insert(R,K)}}else{if(Object.keys){var S=Object.keys(N),J=S.length;while(J--){Q=S[J];F=N[Q];K=s.match(P,G,Q,F);if(K){s.traverse(P,K,Q,F)}}}else{for(Q in N){if(N.hasOwnProperty(Q)){F=N[Q];K=s.match(P,G,Q,F);if(K){s.traverse(P,K,Q,F)}}}}}}},elementType:function x(G,F,E,H){if(F){var I=F.nodeName;if(typeof I==="string"){if(c.test(I)){return"input"}if(g.test(I)){return"image"}}}},map:false,insert:function(F,E){if(E.weld&&E.weld.insertBefore){F.insertBefore(E,E.weld.insertBefore)}else{F.appendChild(E)}},set:function C(I,G,F,J){if(s.map&&s.map(I,G,F,J)===false){return false}if(d){n("- SET: value is",J.tagName)}var H=s.elementType(I,G,F,J),E=false;if(J&&J.nodeType){if(G.ownerDocument!==J.ownerDocument){J=G.ownerDocument.importNode(J,true)}else{if(J.parentNode){J.parentNode.removeChild(J)}}while(G.firstChild){G.removeChild(G.firstChild)}G.appendChild(J);E=true}else{if(H==="input"){G.setAttribute("value",J);E=true}else{if(H==="image"){G.setAttribute("src",J);E=true}else{G.textContent=J;E=true}}}return E},match:function v(J,I,H,K){if(typeof t.alias[H]!=="undefined"){if(typeof t.alias[H]==="function"){H=t.alias[H](J,I,H,K)||H}else{if(t.alias[H]===false){return false}else{H=t.alias[H]}}}if(H&&H.nodeType){return H}if(I){if(I.querySelector){return I.querySelector("."+H+",#"+H+',[name="'+H+'"]')}else{var G=I.getElementsByTagName("*"),E=G.length,L,F;for(F=0;F<E;F++){L=G[F];if(L.id===H||L.name===H||L.className.split(" ").indexOf(H)>-1){return L}}}}}},B=y.parentNode,q,r,z,d;if(D){for(r in D){if(D.hasOwnProperty(r)){t[r]=D[r]}}}d=t.debug;for(q in s){if(s.hasOwnProperty(q)){currentOp=s[q];z=t[q]||s[q];if(d){z=j(q,z)}s[q]=z}}s.traverse(null,y,null,u);if(t.debug){o.log(B.innerHTML)}}})((typeof exports==="undefined")?window:exports);
View
7 package.json
@@ -1,6 +1,6 @@
{
"name": "weld",
- "version": "0.2.0",
+ "version": "0.2.1",
"description": "Template antimatter for javascript",
"keywords": ["templates", "templating", "jsdom", "unobtrusive"],
"author" : "hij1nx <hij1nx@gmail.com> http://twitter.com/hij1nx",
@@ -11,11 +11,10 @@
"licenses": [{"type": "MIT"}],
"repositories": [{
"type": "git",
- "url": "git://github.com/tmpvar/unobtrusive.jsdom.org.git"
+ "url": "git@github.com:hij1nx/weld.git"
}],
"dependencies": {
- "jsdom" : ">= 0.2.0",
- "colors" : "*"
+ "jsdom" : ">= 0.2.0"
},
"devDependencies" : {
"nodeunit" : "*"
View
2  test/getTemplate.js
@@ -1,7 +1,7 @@
var jsdom = require('jsdom')
,path = require("path")
,jqpath = path.join(__dirname, 'vendor', 'jquery.js')
- ,wpath = require('weld').filepath;
+ ,wpath = require(__dirname + '/../lib/weld').filepath;
module.exports = function (name, fn) {
jsdom.env(path.join(__dirname, 'test.html'), [jqpath, wpath], function(errors, window) {
Please sign in to comment.
Something went wrong with that request. Please try again.