editor: menu view
[fnpeditor.git] / src / editor / views / menu / menu.js
1 define(function(require) {
2     
3 'use strict';
4
5 var $ = require('libs/jquery'),
6     Backbone = require('libs/backbone'),
7     template = require('libs/text!./menu.html'),
8     itemTemplate = require('libs/text!./menuitem.html');
9
10
11 var Menu = function() {
12     this.dom = $(template);
13     this.actions = [];
14 };
15 $.extend(Menu.prototype, {
16     addAction: function(action) {
17         var item = new MenuItem(action);
18         item.on('execute', function() {
19             this.close();
20             action.execute();
21         }.bind(this));
22
23         this.actions.push(action);
24         this.dom.find('ul').append(item.dom);
25     },
26     close: function() {
27         this.dom.remove();
28     },
29     show: function() {
30         this.dom.find('.dropdown-menu').dropdown('toggle');
31     },
32     updateContextParam: function(k, v) {
33         this.actions.forEach(function(action) {
34             action.updateContextParam(k, v);
35         });
36     }
37 });
38
39 var MenuItem = function(action) {
40     this.action = action;
41     this.dom = $(itemTemplate);
42     
43     action.on('paramsChanged', function() {
44         this.render();
45     }.bind(this));
46
47     this.dom.on('click', function() {
48         if(this.action.getState().allowed) {
49             this.trigger('execute');
50         }
51     }.bind(this));
52
53     this.render();
54 };
55 $.extend(MenuItem.prototype, Backbone.Events, {
56     render: function() {
57         var state = this.action.getState();
58         this.dom.find('a').text(state.label || '?');
59         this.dom.toggleClass('disabled', !state.allowed);
60     }
61 });
62
63
64 return Menu;
65
66 });