'use babel';

export default {
	event1: null,
	event2: null,
	timer1: null,
	
	activate(state) {
		this.event1 = atom.workspace.observeTextEditors(this.callback.bind(this));
		this.event2 = atom.grammars.onDidAddGrammar(this.callback_grammar_added.bind(this));
	},
	
	callback(editor) {
		if (editor.getGrammar() != atom.grammars.nullGrammar) {
			return;
		}
		
		line = editor.lineTextForBufferRow(0);
		if (! line.startsWith('#!')) {
			return;
		}
		
		if (! line.endsWith('python')) {
			return;
		}
		
		grammar = atom.grammars.grammarForScopeName('source.python');
		if (grammar == null) {
			return;
		}
		
		editor.setGrammar(grammar);
	},
	
	callback_grammar_added(grammar) {
		if (this.timer1 != null) {
			clearTimeout(this.timer1);
			this.timer1 = null;
		}
		
		var self = this;
		this.timer1 = setTimeout(function(){self.callback_all_grammars_loaded();}, 500);
	},
	
	callback_all_grammars_loaded() {
		this.timer1 = null;
		var editors = atom.workspace.getTextEditors();
		for (i = 0; i < editors.length; i++) {
			this.callback(editors[i]);
		}
	},
	
	deactivate() {
		if (this.event1 != null) {
			this.event.dispose();
		}
		
		if (this.event2 != null) {
			this.event2.dispose();
		}
		
		if (this.timer1 != null) {
			clearTimeout(this.timer1);
			this.timer1 = null;
		}
	}
};

@@ -7,16 +7,61 @@
 abel';%0A%0A
+import %7B CompositeDisposable %7D from 'atom';%0A%0A
 export d
@@ -79,24 +79,9 @@
 vent
-1: null,%0A%09event2
+s
 : nu
@@ -131,17 +131,80 @@
 his.
-event1 = 
+subscriptions = new CompositeDisposable();%0A%09%09this.subscriptions.add(%0A%09%09%09
 atom
@@ -258,16 +258,20 @@
 d(this))
+%0A%09%09)
 ;%0A%09%09this
@@ -275,17 +275,30 @@
 his.
-event2 = 
+subscriptions.add(%0A%09%09%09
 atom
@@ -362,16 +362,20 @@
 d(this))
+%0A%09%09)
 ;%0A%09%7D,%0A%09%0A
@@ -1208,17 +1208,17 @@
 is.event
-1
+s
  != null
@@ -1234,16 +1234,17 @@
 is.event
+s
 .dispose
@@ -1245,35 +1245,25 @@
 ispose();%0A%09%09
-%7D%0A%09%09%0A%09%09if (
+%09
 this.event2 
@@ -1264,45 +1264,16 @@
 vent
-2 !
+s 
 = null
-) %7B%0A%09%09%09this.event2.dispose()
 ;%0A%09%09

use a CompositeDisposable instead of saving each event in a variable