加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的事件怎么做?

发布时间:2020-12-16 20:25:11 所属栏目:百科 来源:网络整理
导读:我来自C#背景,刚刚开始使用Ruby编程.事实是,我需要知道如何在课堂上提高事件,以便在需要发生的时候触发各种观察者. 问题是我对Ruby的书甚至不提及事件,更不用说提供例子了.有人能帮我吗? 解决方法 我尝试用Ruby编写一个GUI库,主要是Ruby.最终我放弃了这么慢
我来自C#背景,刚刚开始使用Ruby编程.事实是,我需要知道如何在课堂上提高事件,以便在需要发生的时候触发各种观察者.

问题是我对Ruby的书甚至不提及事件,更不用说提供例子了.有人能帮我吗?

解决方法

我尝试用Ruby编写一个GUI库,主要是Ruby.最终我放弃了这么慢,从未放过它.但是我写了一个事件系统,我试图比C#更容易.我重写了几次,使其更容易使用.我希望它有所帮助.
class EventHandlerArray < Array
  def add_handler(code=nil,&block)
    if(code)
      push(code)
    else
      push(block)
    end
  end
  def add
    raise "error"
  end
  def remove_handler(code)
    delete(code)
  end
  def fire(e)
    reverse_each { |handler| handler.call(e) }
  end
end

# with this,you can do:
#  event.add_handler
#  event.remove_handler
#  event.fire (usually never used)
#  fire_event
#  when_event
# You just need to call the events method and call super to initialize the events:
#  class MyControl
#    events :mouse_down,:mouse_up,#           :mouse_enter,:mouse_leave
#    def initialize
#      super
#    end
#    def when_mouse_up(e)
#      # do something
#    end
#  end
#  control = MyControl.new
#  control.mouse_down.add_handler {
#    puts "Mouse down"
#  }
# As you can see,you can redefine when_event in a class to handle the event.
# The handlers are called first,and then the when_event method if a handler didn't
# set e.handled to true. If you need when_event to be called before the handlers,# override fire_event and call when_event before event.fire. This is what painting
# does,for handlers should paint after the control.
#  class SubControl < MyControl
#    def when_mouse_down(e)
#      super
#      # do something
#    end
#  end
def events(*symbols)
  # NOTE: Module#method_added

  # create a module and 'include' it
  modName = name+"Events"
  initStr = Array.new
  readerStr = Array.new
  methodsStr = Array.new
  symbols.each { |sym|
    name = sym.to_s
    initStr << %Q{
      @#{name} = EventHandlerArray.new
    }
    readerStr << ":#{name}"
    methodsStr << %Q{
      def fire_#{name}(e)
        @#{name}.fire(e)
        when_#{name}(e) if(!e.handled?)
      end
      def when_#{name}(e)
      end
    }
  }
  eval %Q{
    module #{modName}
      def initialize(*args)
        begin
          super(*args)
        rescue NoMethodError; end
        #{initStr.join}
      end
      #{"attr_reader "+readerStr.join(',')}
      #{methodsStr.join}
    end
    include #{modName}
  }
end

class Event
  attr_writer :handled
  def initialize(sender)
    @sender = @sender
    @handled = false
  end
  def handled?; @handled; end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读