Referring URL : http://davidsulc.com/blog/2012/04/22/a-simple-backbone-marionette-tutorial-part-2/
I am naive into backbone and event Aggregator. Can you please let me know the reason to use the following line of code.
this.model.addVote();
MyApp.vent.trigger("rank:down", this.model);
it seems some other possibility could be
this.model.addVote();
this.model(rankDown);
or the other way
MyApp.vent.trigger("addVote", this.model
Kindly explain thanks.
Running Sample: http://jsfiddle.net/Irfanmunir/966pG/29/
Events in general are useful for decoupling objects from each other, while still allowing them to communicate. The event aggregator pattern (or pub/sub pattern) at an application level allows further decoupling by having a 3rd party in the mix: publisher, aggregator, subscriber. This way, neither the publisher nor subscriber have to know about each other. They each know about the event aggregator only.
I wrote up a small article on this a while back:
http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/
In this case, the events are used because the model needs to be manipulated in the context of the collection that it belongs to. Rather than going through the model to get to the collection (which it might not be directly assigned to... models are not required to be part of a collection), it's easier and more flexible to raise this event and have it handled somewhere more appropriate.
Related
How may I choose subscriber while publishing event using EventAggregator in Calirburn Micro?
I have four subscribers for some particular message at single time but I want to send notification to one of them while publishing the message. Subscribers are generic here and I'm interested only in appropriate(one) subscriber suitable for the publisher type.
Thanks in advance.
My two suggestions would be:
Define a new kind of Event that only the target you're interested in gets subscribed to, or...
Let each subscriber decide if that message is for them or not (by including something in the Arguments that helps them discriminate, like an ID or some other identifying property)
Those are the only two correct options for a Publisher-Subscriber pattern, IIRC.
I have recently looked at Backbone.Marionette.
It mentions the Event Aggregator in a way that seems to be something new.
https://github.com/toekneestuck/edgefonts-preview/blob/master/components/backbone.marionette/docs/marionette.eventaggregator.md
However I don't really see the added benefit to normal events. Doesn't following Code provide you the same?
var dispatcher = _.clone(Backbone.Events)
These are almost exactly the same things. (check the code)
The difference is that EventAggregators is a "class" which can be instantiated (wherea Backbone.Events act more as a mixin).
Being a "class", EventAggregators can be extended.
EventAggregators.extend({ /* your new methods */ });
The difference is really small, but goes a long way in reducing boilerplate necessary to create a event hub with custom prototype methods - and extending them in sub-eventAggregator.
In my example I have a parent model (ModelParent) with two collections (A and B), which hold ModelA's and ModelB's respectively. There are associated views for each model (ViewParent, ViewA, and ViewB)
I would like a function in ViewA to add a new item to CollectionB.
What's the best way to do this? (couple of possibilities below):
Should ViewA be passed a reference to ViewParent, when it is created? How best to do this? (as far as I know there is now in build parent reference)
Should ViewParent be stored in the window scope, so that ViewA can refrence it like window.ViewA? (This seems wrong to me)
Another alternative than listening directly to events from your collection, is the use of an eventBus. Derick Bailey from Los techies wrote a nice article where he introduces the idea of communication between different components (in his case views) via an eventBus.
If you are firm with coffeescript - and possibly even if you're not - you should also check this nice extension from Adam Thurlow.
Side note: If your situation simply requires communication between the two elements an eventBus is most likely overkill, although the idea is imho ultra simple. Apart from that, I am of the believe, that a central component for communication is worth the effort as it simplifies messaging, supports decoupling and gives your architecture a reliable consistency.
I would consider thinking about it a different way. I believe it would be cleaner if you didn't have to pass references all around your views. Instead, use backbone's built in event model and keep the "add new item to CollectionB" logic inside ViewParent. When ViewParent instantiates ViewA, you could immediately bind to an event on it:
this.viewA = new ViewA({});
this.viewA.bind("some_event_that_requires_adding_to_collection", this.onViewAEvent);
Inside ViewA, whenever you want to add to CollectionB, just trigger the event:
this.trigger("some_event_that_requires_adding_to_collection", itemIWantToAdd);
Add additional arguments to the trigger call to pass them to any callback bound to the event.
Presuming you have an email folder and messages in it. Each message has Body property, which needs to be loaded async and notify you when done, how would you approach this?
1 - Message.LoadBody() + event Message.BodyLoadComplete
2 - Message.LoadBody(Action completeDelegate)
For the sake of completeness WPF and Prism are involved.
Thanks!
Edit:
Message will be a UI entity which will wrap a IMessage interface (that is not UI Ready (no INPC)), so the reason i'm asking is that we have to settle for an interface between UI and business layer.. IMessage. (The Business layer will be using an Imap library that already has some async pattern, but we don't want to depend too much on any imp, thats why i'm trying to figure out the best interface ..
If you're using .NET 4, I'd use:
Task<string> LoadBodyAsync()
(You might want to implement this using TaskCompletionSource<TResult>.)
The caller can then add continuations etc however they wish... and most importantly, in the brave new world of .NET 4.5 and C# 5, this will work seamlessly with the async/await features.
Of your two options:
Message.LoadBody() // Plus an event, Message.BodyLoadComplete
// or ...
Message.LoadBody(Action completeDelegate)
The event option is more flexible and may sometimes be less painful to use. If you don't care when or if LoadBody completes, then you aren't forced to provide a fake callback. And you can bind the completion event to multiple event handlers, which might sometimes be useful (e.g. if multiple UI controls need to be updated).
Both your solutions are non-typical, though. The typical "old" way to do this is for LoadBody to be split into BeginLoadBody and EndLoadBody, and give the user an IAsyncResult. See this article. The typical "new" way to do it is outlined in Jon Skeet's answer.
If you're using Prism you should consider using the EventAggregator and publishing a message to indicate a mail has loaded. This will allow you to easily have multiple loosely-coupled subscribers for this "event".
Using the EventAggregator is an elegant solution for publishing events, and leads to a much cleaner and decoupled architecture which is easier to extend. For instance, if you wish to add a new feature to email loading such as progress indication, you can simply subscribe to the EmailLoaded message and you're done, you don't have to tightly couple your new component to emails via an event or callback, they do not need to know about each other.
I have often times wondered about it but now that I have encountered a piece of logic that incorporates it, I thought I should go ahead and get some help on deciphering the fundamentals. The problem is as follows, I am looking at a WPF application that is utilizing the Composite Application Library. Within the source of the application I came across the following line of code in the Presentation of a view. For the sake of convinience I will call it Presentation A:
private void OnSomethingChanged(SomeArgumentType arguement)
{
UnityImplementation.EventAggregator.GetEvent<EventA>().Publish(null);
}
When I saw the method Publish in the above given method, my gut told me there must be a Subscribe somewhere and in another class, I will call it Presentation B there was the following:
UnityImplementation.EventAggregator.GetEvent(Of EventA).Subscribe(AddressOf OnSomeEventA)
There was a private function in the same class called OnSomeEventA that had some logic in it.
My question here is that how is everything wired over here? What exactly is achieved by the 'Publish' 'Subscribe' here? When 'something' changes, how does the compiler know it has to follow the logic in OnSomethingChanged that will 'Publish' an event that is 'Subscribed' by another class where the logic of the event handler has been described? It will be great to understand the underlying wiring of this process.
Thanks
The first time GetEvent<T> is called for each event (identified by the type parameter T) the EventAggregator creates an empty list of methods to call when that event is published. Typically, this will happen immediately before the first call to Publish or Subscribe (as in your examples).
Then:
Whenever Subscribe is called a method is added to the list.
Whenever Publish is called it walks through the list and makes those calls.
So, the call to Publish() in Presentation A results in all of the methods that have been registered by calling Subscribe being called, which in your example would include Presentation B's OnSomeEventA method.
Try setting a breakpoint in the OnSomeEventA method and take a look at the stack, and don't forget the source is available, too!