smartxml: Document can create node from xml string
authorAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Wed, 11 Dec 2013 12:14:04 +0000 (13:14 +0100)
committerAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Sun, 15 Dec 2013 21:32:50 +0000 (22:32 +0100)
src/smartxml/smartxml.js
src/smartxml/smartxml.test.js

index 52236b6..d9e44be 100644 (file)
@@ -268,17 +268,22 @@ $.extend(Document.prototype, Backbone.Events, {
 
     createDocumentNode: function(from) {
         if(!(from instanceof Node)) {
-            if(from.text !== undefined) {
-                /* globals document */
-                from = document.createTextNode(from.text);
+            if(typeof from === 'string') {
+                from = parseXML(from);
+                this.normalizeXML(from);
             } else {
-                var node = $('<' + from.tagName + '>');
+                if(from.text !== undefined) {
+                    /* globals document */
+                    from = document.createTextNode(from.text);
+                } else {
+                    var node = $('<' + from.tagName + '>');
 
-                _.keys(from.attrs || {}).forEach(function(key) {
-                    node.attr(key, from.attrs[key]);
-                });
+                    _.keys(from.attrs || {}).forEach(function(key) {
+                        node.attr(key, from.attrs[key]);
+                    });
 
-                from = node[0];
+                    from = node[0];
+                }
             }
         }
         var Factory, typeMethods, typeTransformations;
@@ -309,11 +314,16 @@ $.extend(Document.prototype, Backbone.Events, {
     loadXML: function(xml, options) {
         options = options || {};
         this._defineDocumentProperties($(parseXML(xml)));
+        this.normalizeXML(this.dom);
         if(!options.silent) {
             this.trigger('contentSet');
         }
     },
 
+    normalizeXML: function(nativeNode) {
+        void(nativeNode); // noop
+    },
+
     toXML: function() {
         return this.root.toXML();
     },
index d82f823..cc68cdd 100644 (file)
@@ -60,6 +60,15 @@ describe('smartxml', function() {
             expect(emptyTextNode.getText()).to.equal('', 'empty ok');
             expect(nonEmptyTextNode.getText()).to.equal('alice', 'non empty ok');
         });
+
+        it('creates nodes from xml strings', function() {
+            var doc = getDocumentFromXML('<div></div>'),
+                node = doc.createDocumentNode('<a>Alice<b></b></a>');
+            expect(node.getTagName()).to.equal('a');
+            expect(node.contents().length).to.equal(2);
+            expect(node.contents()[0].getText()).to.equal('Alice');
+            expect(node.contents()[1].getTagName()).to.equal('b');
+        });
     });
 
     describe('DocumentNode', function() {