760208fc6cf963cd437f9ca70020bc65edf61e6c
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / wlxmlListener.js
1 define([
2 'libs/jquery',
3 'modules/documentCanvas/canvas/utils',
4 ], function($, utils) {
5     
6 'use strict';
7
8 var Listener = function(canvas) {
9     this.canvas = canvas;
10 };
11
12 $.extend(Listener.prototype, {
13     listenTo: function(wlxmlDocument) {
14         if(wlxmlDocument === this.wlxmlDocument) {
15             return;
16         }
17         this.wlxmlDocument = wlxmlDocument;
18
19         wlxmlDocument.on('change', function(event) {
20             var handler = handlers[event.type];
21             if(handler) {
22                 handler.bind(this)(event);
23             }
24         }, this);
25
26         wlxmlDocument.on('operationEnd', function() {
27             this.canvas.triggerSelectionChanged();
28         }, this);
29
30         wlxmlDocument.on('contentSet', function() {
31             this.canvas.loadWlxmlDocument(wlxmlDocument);
32         }, this);
33     }
34 });
35
36
37 var _metadataEventHandler = function(event) {
38     var element = utils.getElementForNode(event.meta.node);
39     element.handle(event);
40 };
41
42
43 var handlers = {
44     nodeAttrChange: function(event) {
45         var element = utils.getElementForNode(event.meta.node),
46             newElement;
47         if(event.meta.attr === 'class') {
48             if(element.wlxmlNode.getClass() !== event.meta.attr) {
49                 if(event.meta.node.isRoot()) {
50                     this.canvas.reloadRoot();
51                 } else {
52                     newElement = this.canvas.createElement(event.meta.node);
53                     element.dom.replaceWith(newElement.dom);
54                 }
55             }
56
57         } else {
58             element.handle(event);
59         }
60     },
61     nodeAdded: function(event) {
62         if(event.meta.node.isRoot()) {
63             this.canvas.reloadRoot();
64             return;
65         }
66
67         var containingNode = event.meta.node.parent(),
68             containingElement = utils.getElementForNode(containingNode);
69
70         containingElement.handle(event);
71     },
72     nodeMoved: function(event) {
73         return handlers.nodeAdded.call(this, event); //
74         //
75     },
76     nodeDetached: function(event) {
77         var element = utils.getElementForDetachedNode(event.meta.node, event.meta.parent);
78         element.handle(event);
79     },
80     nodeTextChange: function(event) {
81         var element = utils.getElementForNode(event.meta.node);
82         element.setText(event.meta.node.getText());
83     },
84
85     metadataChanged: _metadataEventHandler,
86     metadataAdded: _metadataEventHandler,
87     metadataRemoved: _metadataEventHandler
88 };
89
90 return {
91     create: function(canvas) {
92         return new Listener(canvas);
93     }
94 };
95
96 });