Toon posts:

[JS] this.setLine is not a function ... scoping probleem?

Pagina: 1
Acties:

Onderwerpen


Acties:
  • 0 Henk 'm!

Verwijderd

Topicstarter
Ook ik ben bezig met een online editor. Hiervoor heb ik o.a. de volgende code:
JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Object.extend(textEditor.prototype, {
  createGutter : function() {
    var target = this.textarea;  
    gutter = createNode('textarea', {'id' : target.name + '-gutter'});
    
    target.onkeydown = function() { this.countLines(gutter); this.setLine(); }
    target.onkeyup   = function() { this.countLines(gutter); this.setLine(); }
  },

  setLine : function(el) {
    el.scrollTop = this.scrollTop;
  },
  
  countLines : function(el) {
    var count = el.value.split('\n').length - 1;
    var lines = this.textarea.value.split('\n').length;
    if (lines != count) {
      var string = '';
      for (var no = 1; no <= lines; no++) {
        string += no + '\n';
      }
      el.innerHTML = string;
    }
  }
});

Als ik deze code run, krijg ik als error:
this.countLines is not a function: line 6
Mijn vraag is: wat doe ik verkeerd? Voor zover is weet maak ik een valide functie-call...?

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 15:40

crisp

Devver

Pixelated

Binnen je anonymous functie verwijst 'this' naar 'target', als je naar je textEditor instance wilt verwijzen dan zal je dat zo moeten doen:
JavaScript:
1
2
3
var self = this;
target.onkeydown = function() { self.countLines(gutter); self.setLine(); }
target.onkeyup   = function() { self.countLines(gutter); self.setLine(); }

Intentionally left blank


Acties:
  • 0 Henk 'm!

Verwijderd

Topicstarter
crisp, thanks! Ik blijf "this" wel erg lastig vinden... :(

Acties:
  • 0 Henk 'm!

Verwijderd

this verwijst altijd naar het object wat de method aanroept, dat moet je onthouden, in dit geval is dat dus target