代码之家  ›  专栏  ›  技术社区  ›  BvuRVKyUVlViVIc7

观察员vs.回调

  •  32
  • BvuRVKyUVlViVIc7  · 技术社区  · 17 年前

    我考虑过使用观察者或回调。

    F.e.您可以执行以下操作:

    # User-model
    class User << AR
      after_create :send_greeting!
    
      def send_greeting!
        UserNotifier.deliver_greeting_message(self)
      end
    
    end
    
    #observer
    class UserNotifier << AR
      def greeting_message(user)
      ...
      end
    end
    

    或者你可以创建一个观察者,让它在用户被创建时观察。。。

    你推荐什么?

    3 回复  |  直到 17 年前
        1
  •  12
  •   Aaron Digulla    17 年前

    回调更为短暂:将其传递到一个要调用一次的函数中。它是API的一部分,因为您通常不能在不传递回调的情况下调用函数。这个概念与函数的功能紧密结合。通常,您只能传递一个回调。。

    示例:运行线程并在线程终止时调用回调。

        2
  •  45
  •   Michael Johnston    15 年前

    要记住的一个非常重要的区别,与米兰诺沃塔的回答有关,就是ActiveRecord上的回调能够取消正在调用的操作和所有后续回调,而观察者则不能。

    class Model < ActiveRecord::Base
      before_update :disallow_bob
    
      def disallow_bob
      return false if model.name == "bob"
      end
    end
    
    class ModelObserver < ActiveRecord::Observer
      def before_update(model)
        return false if model.name == "mary"
      end
    end
    
    m = Model.create(:name => "whatever")
    
    m.update_attributes(:name => "bob")
    => false -- name will still be "whatever" in database
    
    m.update_attributes(:name => "mary")
    => true -- name will be "mary" in database
    

    观察员只能观察,不能干预。

        3
  •  29
  •   Milan Novota    17 年前