From b5d516652ee4cc58a8a0636074456b344126f7d7 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Aleksander=20=C5=81ukasz?= Date: Thu, 16 Jan 2014 10:34:31 +0100 Subject: [PATCH] smartxml: allow objects set with setData to clone themselves on node cloning --- src/smartxml/smartxml.js | 10 ++++++++++ src/smartxml/smartxml.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/smartxml/smartxml.js b/src/smartxml/smartxml.js index acbe04d..000f722 100644 --- a/src/smartxml/smartxml.js +++ b/src/smartxml/smartxml.js @@ -34,6 +34,16 @@ $.extend(DocumentNode.prototype, { clone: function() { var clone = this._$.clone(true, true); + clone.find('*').addBack().each(function() { + var clonedData = $(this).data(); + _.pairs(clonedData).forEach(function(pair) { + var key = pair[0], + value = pair[1]; + if(_.isFunction(value.clone)) { + clonedData[key] = value.clone(); + } + }); + }); return this.document.createDocumentNode(clone[0]); }, diff --git a/src/smartxml/smartxml.test.js b/src/smartxml/smartxml.test.js index 57f11cc..0883ba7 100644 --- a/src/smartxml/smartxml.test.js +++ b/src/smartxml/smartxml.test.js @@ -86,6 +86,31 @@ describe('smartxml', function() { }); }); + it('can be cloned with its contents and its contents data', function() { + var doc = getDocumentFromXML('
'), + root = doc.root, + div = root.contents()[0]; + + var ClonableObject = function(arg) { + this.arg = arg; + }; + ClonableObject.prototype.clone = function() { + return new ClonableObject(this.arg); + }; + + div.setData('key', 'value'); + div.setData('clonableObject', new ClonableObject('test')); + + var rootClone = root.clone(), + divClone = rootClone.contents()[0], + stringClone = divClone.getData('key'), + objClone = divClone.getData('clonableObject'); + + expect(stringClone).to.equal('value'); + expect(objClone.arg).to.equal('test', 'clonable object got copied'); + expect(objClone !== div.getData('clonableObject')).to.be.equal(true, 'copy of the clonable object is a new object'); + }); + it('knows its path in the document tree', function() { var doc = getDocumentFromXML('text'), root = doc.root, -- 2.20.1