Coffeescript + Atom:绑定监听器

时间:2018-06-25 22:29:48

标签: coffeescript bind atom-editor

我的问题是,如果我在循环上创建侦听器,则侦听器回调函数在被调用时会使用循环索引的最后一个值。我想这是绑定回调函数的问题,但我不知道怎么做。请参见以下示例:

{TextEditor, Disposable, Range, Point, Atom} = require 'atom'

class TestGuy
  constructor:(n,id) ->
    @marker = atom.workspace.getActiveTextEditor().markBufferRange([[n,0],[n+1,0]])
    @id = id


class TestGuys
  constructor:() ->
    @markID = 0
    @disposables = []

  bundle:() ->
    for i in [0...2]
      testguy = new TestGuy([i,@markID)
      console.log(testguy.id) #prints 0,1 as i expect
      @markID += 1
      @disposables.push testguy.marker.onDidChange (event) =>
        console.log(testguy.id) #when i invalidate markers, these callbacks print 1,1, but i expected 0,1 !

atom.commands.add 'atom-text-editor', 'custom:test', ->
  testobject = new TestGuys()
  testobject.bundle()

因此,当调用回调时,即使第一个回调函数是为i = 0定义的,它们都使用i = 1

0 个答案:

没有答案