kineticjs中的事件处理

时间:2013-01-28 20:47:23

标签: javascript javascript-events event-handling coffeescript kineticjs

在下面的代码中,事件在开始时(页面加载时)被调用10次,因为有10个矩形带有一个on“click”事件。 但是,当我真正点击一个矩形时,事件并没有影响。

这里是代码((我用rect替换了图像以便于更容易处理)

width = window.innerWidth   || document.documentElement.clientWidth || document.body.clientWidth || 0
height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0

class Gallery 
    constructor: (config) -> 
        @first_xpos          = 0
        @first_ypos          = 0
        @vertical_spacing    = 20
        @horizontal_spacing  = 10
        @current_xpos        = @first_xpos
        @current_ypos        = @first_ypos
        @current_img_in_line = 1
        @max_pics_in_line    = 3
        @stage       = new Kinetic.Stage(config)
        @images_layer = new Kinetic.Layer
        @message_layer = new Kinetic.Layer()
        @image_width = 100
        @image_height = 100

    addImages: () ->
        for i in [0...10]
          ori = new Kinetic.Rect
                    x: @current_xpos 
                    y: @current_ypos
                    fill: 'green'
                    draggable: false
                    width: @image_width
                    height: @image_height
          ori.on('click', @.testfunc() )
          @images_layer.add ori
          @calculate_position()
        @stage.add @images_layer
        @stage.add @message_layer

    testfunc:  -> 
        console.log "event when is_clicked"

    calculate_position: ->
        @current_img_in_line++
        @current_xpos = @current_xpos + @image_width + @horizontal_spacing
        if @current_img_in_line > @max_pics_in_line
           @current_xpos = @first_xpos
           @current_ypos = @current_ypos + @vertical_spacing + @image_height
           @current_img_in_line = 1

window.onload = -> 
  stage = new Gallery
                container: "gallery_container"
                width:  width
                height: height
   stage.addImages()

1 个答案:

答案 0 :(得分:1)

错误:

ori.on('click', @.testfunc() )

“this”(“@”)不是Gallery类的实例。 “@”链接到Kinetic.Rect实例。你可以这样做:

ori.on 'click', =>
  @testfunc()

如何“=>”适用于咖啡:http://coffeescript.org/#fat_arrow 您编辑的代码:http://jsfiddle.net/lavrton/tDVy6/3/