Created
March 10, 2009 16:20
-
-
Save kangax/76965 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Element#clone(@element, deep) -> Element | |
| * | |
| * Returns a duplicate of an element. | |
| * A wrapper around DOM Level 2 Node::cloneNode, | |
| * which takes care of clone's expando properties defined by Prototype | |
| * | |
| * `deep` argument is passed along to a an underlying `cloneNode` | |
| * and affects cloning correspondingly - i.e. skipping child nodes if `false` | |
| **/ | |
| clone: function(element, deep) { | |
| if (!(element = $(element))) return; | |
| var clone = element.cloneNode(deep); | |
| clone._prototypeUID = void 0; | |
| if (deep) { | |
| var descendants = Element.select(clone, '*'), | |
| i = descendants.length; | |
| while (i--) { | |
| descendants[i]._prototypeUID = void 0; | |
| } | |
| } | |
| return clone; | |
| } | |
| ... | |
| testElementClone: function() { | |
| var element = new Element('div', { | |
| className: 'foo', | |
| title: 'bar' | |
| }); | |
| // add child | |
| element.update('<span id="child">child node</span>'); | |
| // add observer | |
| element.observe('click', Prototype.emptyFunction); | |
| // add observer on a child | |
| element.down('span').observe('dblclick', Prototype.emptyFunction); | |
| var shallowClone = element.clone(); | |
| var deepClone = element.clone(true); | |
| var assertCloneTraits = (function(clone) { | |
| this.assert(clone); // exists | |
| this.assert(clone.show); // is extended | |
| this.assertEqual('DIV', clone.nodeName.toUpperCase()); // proper nodeName | |
| this.assertEqual('foo', clone.className); // proper attributes | |
| this.assertEqual('bar', clone.title); | |
| this.assert(!clone._prototypeUID); // _prototypeUID does not exist | |
| }).bind(this); | |
| // test generic traits of both deep and shallow clones first | |
| assertCloneTraits(shallowClone); | |
| assertCloneTraits(deepClone); | |
| // test deep clone traits | |
| this.assert(deepClone.firstChild); | |
| this.assertEqual('SPAN', deepClone.firstChild.nodeName.toUpperCase()); | |
| this.assert(!deepClone.down('span')._prototypeUID); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment