Share settings between a group of Backbone.js models/views - backbone.js

I am working on a UI, using Backbone + Marionette.js, which displays the same Widget multiple times on a single page. I am struggling with whats the best way to contain events inside each widget. Lets say each widget displays a selected friend's Facebook information (interests, status feed, mutual friends). If the user changes the selected friend for that specific widget what would be the best way to update the models that are part of that widget?
Here is how I am thinking of solving this ...
Create Setting Model - when user selects a different friend inside a widget the Friend select view updates the Setting model.
Approach 1:
Controller listens to the setting model on "change" events and in turn updates all the relevant models. Each model will never know of the setting model.
Approach 2:
Pass setting model to each Model's options and each model listen's to the setting model and when it changes it does whatever it needs to (reload, etc).
These are the 2 approaches that come to my mind. I feel like I am liking the Approach 1 better, but I would appreciate any feedback from people that have used Backbone in a similar fashion.
Thanks,
Habeel

I would go for approach 2 using a singleton setting model as you suggested. That way the views or models listening to the settings are responsible for doing the updating. Approach 1 has two potential pitfalls. If you move the logic of what actually happens to the controller, it can become convoluted and complex. If the controller just reacts to change events on the settings model and propagate them to other models and views, then there seem to be little reason for it to exist.

Another approach could be to make use of Marionette's event aggregator feature. This would allow you to not even need a settings model. Instead, just have the changed model fire a global event that the other models are listening for and adjust accordingly.

Related

reference on backbone updating views, always based on state-change or as eventhandler side-effect?

Pretty cryptic question I admit.
I'm looking for references / best practice in updating views based on a GUI event.
Basically I'm seeing 2 different ways to do this:
every view-change is a reaction to a model-change
Gui event
viewhandler (custom or 2-way binding lib) that
updates Model based on view
the View has a listenTo defined on the MOdel that was updated, which gets invoked
do whatever DOM-changes we want
Do DOM-changes directly in the viewhandler
Gui event
viewhandler (custom or 2-way binding lib) that
updates Model based on view
do whatever DOM-changes we want
the View has a listenTo defined on the MOdel that was updated, which gets invoked
The fist approach seems the most clean to me: it can use validation rules on the model, before changing the DOM and the flow just feels better. However, I can't find any good references to back this up. What is generally considered best practice here?
I wouldn't know what is Overall Internet Agreement on that topic, but working on a fairly large Backbone application with complex views, the first approach is what has proven the most maintainable.
One way to see it is that as you know, Backbone's Views and Backbone's Routers are kinda sharing the workload of what would be an actual Controller in a standard MVC (say, Rails). What that means is that in a view, you'll typically have the logic to translate GUI events (click on X) to Model Change (do Y) and the logic to translate Model Changes (new state after Y) into DOM changes. That doesn't mean the logic needs to be in the same place, those are two separate things. Your model may be shared among multiple views and you need your View to react regardless of where the change is originating. You could also be waiting for the server to answer whatever, and so, the DOM update would be in a callback anyway.
A pattern I have been using a lot lately is to have a _renderUpdating() to update the DOM to let the user know that his action has been taking into account (add a spinner near to whatever triggered the change), but I let events do the actual re-rendering once the server has returned the new model.
There is nothing that prevents you from going with the 2nd approach in simple cases, but as your application grow, you'll be very happy to have more than just a single render() that erases everything (including subviews) and you'll be looking at having a clean break between view -> model (which is the role of a controller) and model -> view to allow for more flexibility.

Reusing WPF MVVM Views

I've inherited an application which uses the view-first MVVMC patern
In the application I've created 2 step process which creates a person and assigns them to a group. To do this I've created a view and corresponding view model (all views have a 1-2-1 relationship with a view model, view models are injected into the View constructor and are registered with the Unity container using the TransientLifetimeManager) called CreatePersonMaster, the view simply contains a region (shown by the dashed line) which sub-views can be loaded into and the view model subscribes to two loosely coupled events, "PersonCreated" and "GroupSelected". The "PersonCreated" event saves a Person entity in a field and the "GroupSelected" event takes the saved Person, creates a Group association and saves them to a database.
This view/view model doesn't do anything until the events get raised so I load the following sub views into my the region.
These views/view models fire the events which get handled by the master view.
I also have an edit view where I want to re-use the select group view.
I can do this by subscribing to the appropriate events in the EditPersonMaster view model.
My question really is, is this the appropriate way to do this? Because I'm using loosely coupled events I don't get any feedback into the sub-View/ViewModels if there's an error when creating/reassigning? I could probably fire another "ErrorBlah" event for the inner view/model to handle and update the view.
Is there another way to do this? Composite commands don't seem to fit the bill but maybe I don't understand them correctly.
Here is how I understood your question: You have persons stored in a database, which have a property/column group. In your UI, you want to create persons and assign the group property. Also, you want to be able to edit the group property of existing persons in a different region/page/master. You want to reuse the control for assigning the group. Your controls fire an event, which is handled by the Master in a way that it creates the entries in the database (is that correct?). Your question is whether this is a good approach and what alternatives you have?
I see two options:
1. Modularize your business logic:
You could inject a data service into your ViewModels, which could access the database directly. This way you can handle errors etc.. directly where they occur and don't have to pass them through the whole system. If you want to notify other modules of changes on the database (specifying the changed dataset or so), you can do so with a composite event. I think of the PRISM modules more as of complete elements, including UI and business logic and keep communication between them as little as possible.
2. Keep your business logic central and share it:
If you want to stick to your architecture, have singleton Model which is injected into the ViewModels. Manage your state in the model and have the ViewModels pick the pieces they want to provide to their view.
Hope I got he point, though...

Backbone.js - Moving data from one view to another

How to send data from one view to another which are on different urls?
A little bit strange question, but OK, let's try to imagine your problem in complex and give an answer.
Imagine application for reading books (like iBooks in web). We have one parent View called ApplicationView which creates several children views and some of them are BookshelfView (available on #bookshelf url) and BookView (available on #book/:id url).
Now, you mark your book as unread from your BookView and you know that your BookshelfView should change the appearance of this book. OK, it is not "moving data from one view to another". You just change the state of your model and your views catch this "change" event and update their html.
Let's describe more complicated situation. Imagine the same application. But at this time you decide to switch portrait orientation to landscape orientation. You make it in one view and you want this change to affect other application views. This can be done in several ways:
Views should stay loosely coupled you should use some kind of mediator pattern.
From Backbone 0.9.9 you can use global Backbone object as Mediator, as Backbone supports Events interface
You can create and additional model for Mediation between two or more views but there is more beautiful solution:
If you have one parent view for several child views you already have that mediator. Just send events to parent view from one view and listen to that events on parent from other view.
I also recommend you check this question

Should views keep track of their model?

This nice article recommends against keeping track of the views belonging to a model inside the model. What about the opposite? It is recommended for views to keep track of the model(s) they are based on?
It seems difficult to imagine to do without. Maybe the recommended way is to use events, or something?
Views always keep a reference to the model. It is accessible through myView.model or myView.collection.models.
Due to the nature of views, I cannot imagine a case where you would want the view to not know about the model. Event binding happens in the view with a reference to a model. (Think about the collection.add event. Wouldn't be possible if you didn't bind to a reference to the collection)
Most of the time the view should know its model cause he is the visualization of the model. So the model can be there without a view, but a view without a model doesn't make much sense.
But as always there are cases where the view should not know its model directly. Think about a basket where a user can add products and maybe he can configure that products. You have different views that visualize the model, like a table with the products, a basket ico with the count of products and a view to show the total amount. All share the same model. So when ever the user creates a new model cause he delete the old one or order something and there after something new, you have to create a new model and pass it to your views. Sure you can to this by fire an event. But you can also pass a proxy for your model to your views, so the views always comunicate with your proxy and they never know that sometimes a new model was created.

Where do I instantiate my Objects in CRUD n-Tiered WinForm App?

Say I have a WinForm CRUD(like) application. I want to follow best practices on this so I try and make it follow OOP and a n-Tiered design.
Unfortunately I am familar with the words but not the practice of them. So lets go with the following example: My CaseNote program. I have a tabbed application where you go to the search tab to find a member and then one of the options is to go to the CaseNote tab to create a new case note, look at existing CaseNotes, or create a follow up CaseNote to a Parent Note. All of this is for the member you selected from the search tab.
So if I am creating objects and passing them around to be used by different forms where should I be instantiating them? I had thought I would have 3 layers; UI, Object, DAL. Where I fall flat is where I instance tho objects. I can't instance them in the object layer, can I? Also, if I instance them on the form how do I pass them from form to form in a quite large app?
CaseNotes Screen Shot
If you want to look at some more words around this problem you want to look at MVP and MVC. (These stand for Model View Controller and Model View Presenter). Some people will shoot me down for saying this but they are quite similar in concept.
The aim of MVP and MVC is to allow you to design your application logic without even having to think about your application apperance. It also allows you to define your user interactions without implementing an actual GUI. Esentially your model is your application logic, your data, your classes which actually do stuff like talk to your database. Your presenter or controller is what interacts with your model and what controls your user interface and reacts to user operations on the interface. Finally your View is your winforms design or your web page.
I'm sure you will be able to find plenty of material on the web about this but to give you some concrete help with this problem should serve to inform and illustrate your reading.
The first thing you need to do is start creating your objects that represent your data. So you will have a CaseNote object which is contains the casenote data. You will have a case note data container of some sort such as a case note database. You can define the logical operations and properties of these as if they where real items.
Then you would move on to define your presenter or controller which will define the operations that you want to support from the GUI. At the same time you should define an Interface that will define for the presenter/controller what operations is can perform on the GUI. So for instance your presenter may expose a method called SearchForCaseNote which takes a string parameter. Your view Interface will expose a method called DisplayCaseNote. When a user clicks on the search button the view will pass through the command to the presenter which will then call the model to get the data. The presenter may format the data at this point, i.e. convert DateTime object to a string and then pass the data back to the view through the interface define method called DisplayCaseNote.
You don't have to use the View interface, you could call into the view directly, but having the interface means you can have many different view implementations.
One last thing i need to mention is where you create these different parts of your application. My view is everything thing should fall out from the presenter/controller. So when you application starts it creates the presenter/controller object which then create and displays your view passing itself as a variable to the view. The presenter/controller can then either create the initial models by loading them from disk or ideally discover them through a dependency injection container like unity. In fact using unity to discover the view implementation is probably a better idea again as it gives you true seperation between view and presenter/controller. When you come to move to another view, (i.e. open another window), your presenter/controller should expose a method such as DisplayDetailPage which the view calls when a button is clicked. This would create the presenter/controller for the next view which would in turn create the view and get a reference to the model.
Hope this helps.
I think you should use the RocketFramework

Resources