观察者与回调 [英] Observers vs. Callbacks

查看:19
本文介绍了观察者与回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我考虑过使用观察者或回调.什么时候应该使用观察者?

i thought about using observers or callbacks. What and when you should use an observer?

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

F.e. you could do following:

# 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

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

or you could create an observer and let it watch when users becomes created...

你推荐什么?

推荐答案

回调的生命周期更短:您将其传递给一个函数以供调用一次.它是 API 的一部分,因为您通常无法在不传递回调的情况下调用该函数.这个概念与函数的作用紧密结合.通常,您只能传递一个回调..

A callback is more short lived: You pass it into a function to be called once. It's part of the API in that you usually can't call the function without also passing a callback. This concept is tightly coupled with what the function does. Usually, you can only pass a single callback..

示例:运行一个线程并提供在线程终止时调用的回调.

Example: Running a thread and giving a callback that is called when the thread terminates.

观察者的寿命更长,并且可以随时附加/分离.同一事物可以有多个观察者,并且它们的生命周期可能不同.

An observer lives longer and it can be attached/detached at any time. There can be many observers for the same thing and they can have different lifetimes.

示例:在 UI 中显示模型中的值并根据用户输入更新模型.

Example: Showing values from a model in a UI and updating the model from user input.

这篇关于观察者与回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆