kiwi.components.Events implemented
[KiwiIRC.git] / client / src / applets / scripteditor.js
1 (function () {
2 var view = Backbone.View.extend({
3 events: {
4 'click .btn_save': 'onSave'
5 },
6
7 initialize: function (options) {
8 var that = this,
9 text = {
10 save: _kiwi.global.i18n.translate('client_applets_scripteditor_save').fetch()
11 };
12 this.$el = $(_.template($('#tmpl_script_editor').html().trim(), text));
13
14 this.model.on('applet_loaded', function () {
15 that.$el.parent().css('height', '100%');
16 $script(_kiwi.app.get('base_path') + '/assets/libs/ace/ace.js', function (){ that.createAce(); });
17 });
18 },
19
20
21 createAce: function () {
22 var editor_id = 'editor_' + Math.floor(Math.random()*10000000).toString();
23 this.editor_id = editor_id;
24
25 this.$el.find('.editor').attr('id', editor_id);
26
27 this.editor = ace.edit(editor_id);
28 this.editor.setTheme("ace/theme/monokai");
29 this.editor.getSession().setMode("ace/mode/javascript");
30
31 var script_content = _kiwi.global.settings.get('user_script') || '';
32 this.editor.setValue(script_content);
33 },
34
35
36 onSave: function (event) {
37 var script_content, user_fn;
38
39 // Build the user script up with some pre-defined components
40 script_content = 'var network = kiwi.components.Network();\n';
41 script_content += 'var input = kiwi.components.ControlInput();\n';
42 script_content += this.editor.getValue() + '\n';
43
44 // Add a dispose method to the user script for cleaning up
45 script_content += 'this._dispose = function(){ network.off(); input.off(); if(this.dispose) this.dispose(); }';
46
47 // Try to compile the user script
48 try {
49 user_fn = new Function(script_content);
50
51 // Dispose any existing user script
52 if (_kiwi.user_script && _kiwi.user_script._dispose)
53 _kiwi.user_script._dispose();
54
55 // Create and run the new user script
56 _kiwi.user_script = new user_fn();
57
58 } catch (err) {
59 this.setStatus(_kiwi.global.i18n.translate('client_applets_scripteditor_error').fetch(err.toString()));
60 return;
61 }
62
63 // If we're this far, no errors occured. Save the user script
64 _kiwi.global.settings.set('user_script', this.editor.getValue());
65 _kiwi.global.settings.save();
66
67 this.setStatus(_kiwi.global.i18n.translate('client_applets_scripteditor_saved').fetch() + ' :)');
68 },
69
70
71 setStatus: function (status_text) {
72 var $status = this.$el.find('.toolbar .status');
73
74 status_text = status_text || '';
75 $status.slideUp('fast', function() {
76 $status.text(status_text);
77 $status.slideDown();
78 });
79 }
80 });
81
82
83
84 var applet = Backbone.Model.extend({
85 initialize: function () {
86 var that = this;
87
88 this.set('title', _kiwi.global.i18n.translate('client_applets_scripteditor_title').fetch());
89 this.view = new view({model: this});
90
91 }
92 });
93
94
95 _kiwi.model.Applet.register('kiwi_script_editor', applet);
96 //_kiwi.model.Applet.loadOnce('kiwi_script_editor');
97 })();