suppose there is a bookList View (with books as it’s model) and some book view (with book as it’s model)
If i want to run a function in every book view. there are a least two ways:
-
maintain an array which contain all book views in bookList view, than run the function directly
-
trigger a custom event on every book model in the books model to make the view run the function.
which one is better?
I really think you should consider a bit more things about your application and you will be guided to the decision by the natural flow of the concept of your application.
So according your methods :
Maintaining an array with views
If you don’t have plenty of those bookView, it can be a solution. In fact, the question you should ask yourself here is do you really need this array only for that function, or could be used for something else.
Trigger a custom event on every book model
This will add to every bookView some identical event listeners and callbacks ( the function itself ). Which will require every bookView the memory share in your browser, for the same information.
I’m also thinking of a third method :
Trigger one custom event in your bookList View, which is listened by your Book views
So you could manage to do this and set an argument at the trigger with the function you want, so basically your code in your book View will be something like :
When you trigger you can do something like
Be ware that when you no longer need the bookView you should turn off the eventlistener :
bookList.off('doThisFunction', cb)from your book View , because you will have a garbage in your bookList event aggregator.