观察者vs.回调 [英] Observers vs. Callbacks
问题描述
我想过使用观察者或回调。
什么时候应该使用观察者?
i thought about using observers or callbacks. What and when you should use an observer?
您可以执行以下操作:
# 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
b $ b
或者你可以创建一个观察者并让它在用户创建时观看...
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.
这篇关于观察者vs.回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!