Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.Radio: what's the advantage of commands and requests over events

It seems like Backbone.Radio provides 2 new abstractions - commands and requests. They're pretty much identical to Backbone.Events, except that they can have only 1 subscriber. Is that it, and if so what advantage do they provide over events?

I plan on using Backbone.Events/Radio with React.js, if that helps.

like image 715
tldr Avatar asked Feb 11 '23 10:02

tldr


1 Answers

I have not actually used Backbone.Radio but do make extensive use of Backbone.wreqr https://github.com/marionettejs/backbone.wreqr which provides an almost identical command service.

In my usage the difference between events and commands is:

For events to work the sender and receiver of an event must both exist and have a reference to each other and the receiver must be in a position to deal with the event properly. This can often be problematic in a fully asynchronous browser environment where different parts of your application are running at the same time.

Commands allow you to decouple the sender and receiver. One object, lets say a View A, can simply send command 'update_user_details'.

My second Object View B sets up a command handler for 'update_user_details' which will change the user details on the screen.

But what if View B does not yet exist, or is not yet rendered. In the event listener pattern you would have to make sure View A exists, that it passes a reference to itself to View B and then you attach an event listener in View B.

With commands it is not a problem, View A sends a command, if no-one has set a handler then nothing bad happens, the command just does nothing.

When View B turns up, totally independent of View A, it sets a handler and will respond to all future commands.

Just a final note about intent:

The event pattern can be thought about in this way: I, View A have just done something, anyone that is interested (the event listeners) can do what they like about it, I View A don't care what you do.

In the command pattern: I View A want someone to do something, I don't care who does it, I just want it done right.

like image 51
Mark Stratmann Avatar answered Feb 13 '23 03:02

Mark Stratmann