1

In trying to call a method on the CodeMirror javascript code editor. I'm new to javascript and trying to understand how object oriented stuff works. I'm having problems calling what I believe are methods. For instance,

var editor = CodeMirror.fromTextArea('code', options);
editor.grabKeys(function(e) { alert("Key event");});

This gives the Uncaught TypeError: Cannot call method 'grabKeys' of undefined. Looking at the editor object reveals that grabKeys seems to be located at editor.__proto__.grabKeys.

How should I be thinking about this?

Tristan
  • 6,776
  • 5
  • 40
  • 63
  • Looks like `CodeMirror.fromTextArea('code', options);` returns `undefined`. Maybe you are passing the wrong arguments to that function? – harto Jun 03 '10 at 00:24
  • If I console.log(editor) it returns as an object I can explore. – Tristan Jun 03 '10 at 00:26

1 Answers1

2

Probably yoour code should be something like this:

var editor = new CodeMirror.fromTextArea('code', options);
editor.grabKeys(function(e) { alert("Key event");});

Notice the 'new' operator..

Here is a good explanation of what prototype method calls are for:

http://www.javascriptkit.com/javatutors/proto.shtml

Vlad
  • 9,180
  • 5
  • 48
  • 67
  • 1
    The linked-to documentation suggests otherwise. – harto Jun 03 '10 at 00:27
  • Sorry didn't see that fromTextArea is a utility function that constructs the object for you. So what is your 'options' object? Can you post the contents here? – Vlad Jun 03 '10 at 00:35
  • They're the default and work. For instance, adding the editor.grabKeys function to this example: http://marijn.haverbeke.nl/codemirror/contrib/python/index.html – Tristan Jun 03 '10 at 00:51
  • Very strange. If I add `editor.grabKeys(function(e) { alert("Asdf");})` in the javascript console it works. If I add it in the html file, right after the editor, it doesn't. Ideas? – Tristan Jun 03 '10 at 00:56
  • Seems this call is async. Need to use `initCallback:`. – Tristan Jun 03 '10 at 01:17