kineticjs 中的事件处理

eventhandling in kineticjs

本文关键字:事件处理 kineticjs      更新时间:2023-09-26

在下面的代码中,在开头(页面加载时)调用该事件 10 次,因为有 10 个矩形带有"单击"事件。但是当我真正单击矩形时的事件不会影响任何事情。

这里是代码(我用 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()

错误在这里:

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

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

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

"=>"在咖啡中的工作原理:http://coffeescript.org/#fat_arrow您编辑的代码:http://jsfiddle.net/lavrton/tDVy6/3/