editor: fix - better handle node removal in various views
[fnpeditor.git] / src / fnpjs / actions.js
1 define(function(require) {
2     
3 'use strict';
4
5 var _ = require('libs/underscore'),
6     Backbone = require('libs/backbone');
7
8 var Action = function(fqName, definition, config, appObject) {
9     this.fqName = fqName;
10     this.definition = definition;
11     this.config = config;
12     this._cache = null;
13     this.appObject = appObject;
14
15     this.params = {};
16 };
17
18 _.extend(Action.prototype, Backbone.Events, {
19     getPluginName: function() {
20         return this.fqName.split('.')[0];
21     },
22     updateContextParam: function(contextName, value) {
23         var changed = false;
24         _.pairs(this.definition.params).forEach(function(pair) {
25             var paramName = pair[0],
26                 paramDesc = pair[1];
27             if(paramDesc.type === 'context' && paramDesc.name === contextName) {
28                  this.params[paramName] = value;
29                  changed = true;
30             }
31         }.bind(this));
32         if(changed) {
33             this._cache = null;
34             this.trigger('paramsChanged');
35         }
36     },
37     updateKeyParam: function(keyName, toggled) {
38         var changed = false;
39         _.pairs(this.definition.params).forEach(function(pair) {
40             var paramName = pair[0],
41                 paramDesc = pair[1];
42             if(paramDesc.type === 'key' && paramDesc.key === keyName) {
43                  this.params[paramName] = toggled;
44                  changed = true;
45             }
46         }.bind(this));
47
48         if(changed) {
49             this._cache = null;
50             this.trigger('paramsChanged');
51         }
52     },
53     updateWidgetParam: function(name, value) {
54         var paramDesc = this.definition.params[name];
55         if(paramDesc.type === 'context' || paramDesc.type === 'key') {
56             throw new Error('');
57         }
58         this.params[name] = value;
59         this._cache = null;
60         this.trigger('paramsChanged');
61     },
62     getState: function() {
63         var gotState;
64         if(!this._cache) {
65             gotState = this.definition.getState.call(this, this.params);
66             if(typeof gotState === 'boolean') {
67                 gotState = {allowed: gotState};
68             }
69             this._cache = _.extend({}, this.definition.stateDefaults || {}, gotState);
70         }
71         if(this._cache === false) {
72             this._cache = {allowed: false};
73         }
74         return this._cache;
75     },
76     execute: function() {
77         var state = this.getState();
78         if(state.allowed) {
79             return state.execute.call(this, this.params, this.appObject);
80         }
81         throw new Error('Execution not allowed');
82     }
83 });
84
85
86 return {
87     Action: Action
88 };
89
90 });