2016-05-01 89 views
0

我有這樣一段代碼在我angular2項目:角2變量不確定

import {bootstrap} from 'angular2/platform/browser'; 
import {Component, AfterViewInit} from 'angular2/core'; 
import {DROPDOWN_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap'; 

@Component({ 
    selector: '<aInsertTable></aInsertTable>', 
    templateUrl: './app/templates/insertTable/insertTable.html', 
    directives: [DROPDOWN_DIRECTIVES], 
}) 
export class InsertTableComponent implements AfterViewInit { 
    public status:{isopen:boolean} = {isopen: false}; 
    public sel: any; 
    public rng: any; 

    ngAfterViewInit(){ 
     jQuery('#editable-area').keyup(function(){ 
      this.sel = window.getSelection(); 
      this.rng = this.sel.getRangeAt(0); 
     }) 
     jQuery('#editable-area').mouseup(function(){ 
      this.sel = window.getSelection(); 
      this.rng = this.sel.getRangeAt(0); 
      console.log(this.sel); 
      console.log(this.rng); 
     }) 
    } 

    public toggleDropdown($event:MouseEvent):void { 
     this.status.isopen = !this.status.isopen; 
    } 

    insertTable(x, y) { 
     console.log(this.sel); 
     console.log(this.rng); 
     if (!$tableId) { 
      var $tableId = 0; 
     } 

     var table = document.createElement("Table"); 
     table.id = "table" + $tableId; 
     table.className = "dynamic-table table"; 
     $tableId++; 

     for (var i = 0; i < y + 1; i++) { 
      var tr = document.createElement('tr'); 
      for (var j = 0; j < x + 1; j++) { 
       var td = document.createElement('td'); 
       tr.appendChild(td); 
      }; 
      table.appendChild(tr); 
     }; 

     this.rng.insertNode(table); 
    } 
} 

現在,這裏的問題:

當我在編輯區單擊或類型,我看到了selrng值在我的控制檯,所以他們被設置,但是,他們似乎只對ngAfterViewInit函數作用域原因當我嘗試插入一個表,我得到selrng未定義。有人能幫我弄清楚我做錯了什麼嗎?謝謝。

回答

1

您需要使用箭頭功能在您的KEYUP和mouseup回調這樣

jQuery('#editable-area').keyup(() => { 
    this.sel = window.getSelection(); 
    this.rng = this.sel.getRangeAt(0); 
}) 

jQuery('#editable-area').mouseup(() => { 
    this.sel = window.getSelection(); 
    this.rng = this.sel.getRangeAt(0); 
    console.log(this.sel); 
    console.log(this.rng); 
}) 

參見https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this

+0

你能給的是什麼功能之間'的區別的解釋()'和'( )=>'?似乎無法找到一個。謝謝。 –

+0

你可以在這個頁面上找到這個行爲的很好的解釋arrow函數https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this – yurzui