0

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

这里是代码(我用 rect 替换了 image 以便于处理):

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()
4

1 回答 1

1

这里的错误:

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

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

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

“=>”如何在咖啡中工作:http://coffeescript.org/#fat_arrow 您编辑的代码:http: //jsfiddle.net/lavrton/tDVy6/3/

于 2013-01-29T01:46:43.777 回答