smartxml: Improving get/set data api
[fnpeditor.git] / src / smartxml / smartxml.js
index 1686abd..1876076 100644 (file)
@@ -1,6 +1,9 @@
 define([
-    'libs/jquery'
-], function($) {
+    'libs/jquery',
+    'libs/underscore',
+    'libs/backbone',
+    'smartxml/events'
+], function($, _, Backbone, events) {
     
 'use strict';
 
@@ -38,6 +41,11 @@ $.extend(DocumentNode.prototype, {
         }
         node.append(this);
     },
+
+    triggerChangeEvent: function(type, metaData) {
+        var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
+        this.document.trigger('change', event);
+    },
 });
 
 var ElementNode = function(nativeNode, document) {
@@ -47,6 +55,22 @@ var ElementNode = function(nativeNode, document) {
 $.extend(ElementNode.prototype, DocumentNode.prototype, {
     nodeType: Node.ELEMENT_NODE,
 
+    setData: function(key, value) {
+        if(value !== undefined) {
+            this._$.data(key, value);
+        } else {
+            this._$.removeData(_.keys(this._$.data()));
+            this._$.data(key);
+        }
+    },
+
+    getData: function(key) {
+        if(key) {
+            return this._$.data(key);
+        }
+        return this._$.data();
+    },
+
     getTagName: function() {
         return this.nativeNode.tagName.toLowerCase();
     },
@@ -74,7 +98,9 @@ $.extend(ElementNode.prototype, DocumentNode.prototype, {
     },
 
     setAttr: function(name, value) {
+        var oldVal = this.getAttr(name);
         this._$.attr(name, value);
+        this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
     },
 
     getAttrs: function() {
@@ -133,8 +159,13 @@ $.extend(ElementNode.prototype, DocumentNode.prototype, {
             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
         };
-    }
+    },
 
+    toXML: function() {
+        var wrapper = $('<div>');
+        wrapper.append(this._$);
+        return wrapper.html();
+    }
 });
 
 var TextNode = function(nativeNode, document) {
@@ -169,8 +200,11 @@ var Document = function(xml) {
     Object.defineProperty(this, 'root', {get: function() {
         return doc.createElementNode($document[0]);
     }});
+    Object.defineProperty(this, 'dom', {get: function() {
+        return $document[0];
+    }});
 };
-$.extend(Document.prototype, {
+$.extend(Document.prototype, Backbone.Events, {
     ElementNodeFactory: ElementNode,
     TextNodeFactory: TextNode,
 
@@ -180,6 +214,10 @@ $.extend(Document.prototype, {
 
     createTextNode: function(nativeNode) {
         return new this.TextNodeFactory(nativeNode, this);
+    },
+
+    toXML: function() {
+        return this.root.toXML();
     }
 });