I'm trying to use Backbone.Marionette, and I read the docs on github about wreqr. So, whats the difference between Event Aggregator, Commands and Request/Response. And when to use one or another?
They bascially all use messaging, and their difference is mainly semantic:
- event aggregator: send a message when something happens. Code somewhere else might be listening for that message, but maybe not
- request/response: have code send a request, and it will expect a response (e.g. send me refreshed data)
- commands: code in one place commands code somewhere else to carry out an action. There usually isn't a return value.
I would like to add to David Sulc's answer.
Request/response is very different from event aggregator and commands. It is used for cases where one part your code requests something from another part of the code. A response would always be expected. Now lets see how event aggregator and commands are different.
Marionette's Event Aggregator allows you to implement publish-subscribe behaviour. Using the 'on' method you can subscribe to an event and bind an event to any object. You cannot implement this binding behaviour using commands. Also you can have multiple objects listening to any particular event. There may also be a case where no object is bound to or listening to any event.
Commands are specifically meant for performing some action in some other part of the code. There can only be 1 handler for a particular command, unlike events where you can have multiple listeners.
So to summarize, the use cases for each would be:
1) Request/Response: When you need some response from another part of the code.
2) Event Aggregator: When you want to bind objects to events
3) Commands: You just want some other part of your code to perform a task.
© 2022 - 2024 — McMap. All rights reserved.