Should views keep track of their model? - backbone.js

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.

Related

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

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.

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...

How to make view model and model communicate?

I am using MVVM pattern for my app. The model actually runs a set of test in parallel and keeps tab of the status of the test including its result. I want the status and result to be displayed in the view. I am stuck at desiging the view model.
The problem is that there are lots of classes and sub class hierarchy in the model in which all the required data to be displayed in the view are stored. Those data are dynamic.
I am not sure how to design the view model now.
I was thinking along these lines - Create a new data structure in view model which reflects what is to be shown in the view and get all the view model will dig through the model to get the required data. In this case I am confused how the model will update the view model whenever a data changes. Or how do the model and view model communicate with each other given that the data are stored in different class and sub classes.
Your view model should have references of all models which required to show data on the view. Then view model should handle events from model classes and fire NotifyPropertyChanged event.
If your view is complex and require lots of models, then you can consider to split your view in multiple views and corresponding view model.
You say the user chooses which data to view, so I imagine your VM could hold an array of Models and an index indicating which is the 'active' one, and only communicate with that one.
For that communication, a solution could be to pass to the model an Action to call when new data is available, and that Action would that trigger a NotifyPropertyChanged in the VM. This would work especially well if you make sure only the 'active' model has that Action while in the others it would be null meaning 'don't trigger updates'.

How to create the ViewModel(s) for many Views sharing the same Model?

This is based on the example from the book:
Pro WPF and Silverlight MVVM by Gary McLean Hall
where the author only insists on how to create the Model for a DB structure (and how to implement the DAL for it).
I am looking for the correct way to create the ViewModel(s).
Here is the database model and the MVVM Model- I suspect it is not quite complete, but the Product is missing the ProductCode:
My Views will be: Pages displaying / editing views for Products, Customers and Orders
I am familiar with the Models / ViewModels implementing / using the INotifyPropertyChange and ObservableCollection, no need to insist on that.
My questions:
How to create the ViewModels in such a way that they would all share the same model
How do I manage the ViewModels? Do I have one Main ViewModel which aggregates all the specific ones? This relates to ViewModel state saving and restoring.
I am particularly interested in how to deal with this: the Model for Order has a List of Products. I will also have to maintain a list of Products for my ProductsViewModel which supports the displaying / editing Views for the Products. How can all be synchronized? Should the OrderModel only have a List of ProductCodes instead? What are the implications in that case?
In general, the thing I am after here is: how to create and manage the ViewModels for Models which implement DB tables with many to many relationships (like Product-Orders). Do we use only the foreign keys as part of the Model objects or do we use a reference to a whole other Model object represented by that foreign key?
To me it sounds like you are thinking about it the wrong way round. When you ask "How to create and manage the ViewModels for the Models which implement DB tables with many to many relationships" it sounds like you are thinking about ViewModels in terms of Models. Which isn't right. A ViewModel is a model of a View - not the Model. You shouldn't be thinking about creating ViewModels for your models, you should be thinking about creating VewModels of your Views.
In fact the model doesn't even come into it until the end. Start with your UI - your View. You then create a logical representation of that View in code so that you can bind to it, your ViewModel. Then finally you implement your ViewModel by accessing your Model to do what ever needs to be done. When you come to design the next View, even though it might contain some of the same data as the first, you would still create a new model for it - another ViewModel. Now the new ViewModel could include some of the same properties at the first ViewModel, which is fine. Remember is is a model of the View not the Model.
Consider an email app, with 2 views, summary and detail. Because there are 2 different Views you have 2 different ViewModels even though the are both pulling data from the same underlying model.
Model SummaryViewModel DetailsViewModel
----- --------------- ----------------
RecipientAddress RecipientAddress
SenderAddress SenderAddress SenderAddress
Subject Subject Subject
Content Content
Now the Summary View is only a summary and doesn't display the RecipientAddress or the Content so consequently those properties don't exist on the SummaryViewModel. The Details View displays more information, so has more properties. This same idea answers your question about foreign keys. Foreign keys are never visible on your View therefore have no business being members of your ViewModel. Your ViewModel cares only about what is required for the View.
In answer to your question "how do you manage the view models": you don't. You don't have to. ViewModel instances usually (not not always) have a one to one relationship with the Views, therefore you don't need to manage them. They only live as long as the view lives. You just create a new instance of the ViewModel when the View is loaded (typically in OnNavigatedTo event handler, see below) and store it in the View's DataContext. If two instances of the View are loaded, then there are two ViewModels. When the View is GC'ed, the ViewModel is too (if it isn't you have a memory leak).
Finally, as for how you should synchronize changes, that can be tricky in a desktop Silverlight app where many views might display concurrently. Fortunately on the Windows Phone we usually only have one view open at a time (although not always). So we can simply tell our ViewModel to refresh each time the page is navigated to:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (DataContext == null)
DataContent = new MyViewModel(); //Create new instance of the ViewModel
else
(MyViewModel)DataContext.Refresh(); //Refresh the existing ViewModel
}
This works well in most cases for more advanced scenarios you could look at the messaging infrasructure provided by a toolkit like Prism or MvvmLight.
Hope this has helped.

MVVM WPF ViewModels for Adding New Entity

My concept for MVVM in WPF is that we have a ViewModel for every Model in your application. This means that if we have Customer class (entity) then we will have CustomerViewModel. The CustomerViewModel will have all the properties which are necessary to represent a customer. The CustomerView usercontrol will be responsible for creating the UI for the Customer model.
Now, let's say that we are adding a new customer. So, we have a form which consists of FirstName, LastName etc. Do we need a ViewModel for this scenario. I mean all I have to do is to take all the input values from TextBox and create a Customer object and then save it to the database. Why should I bother creating a ViewModel for this scenario?
First of all, that is not the main purpose of MVVM, to "mirror" everything. The View should provide the means for a user input, and certainly not process calls to any of the database layers. The ViewModel should be a GUI-agnostic application backbone, and it definetly should handle the creating of customers.
That said, what you should do, is have a ViewModel which represents a workspace for handling customers, and not just a customer ViewModel. If you really want to save on a few objects being created, add to that workspace the possibility to create and add a new customer (not CustomerViewModel). That way, you can have a View of the workspace which has elements for each relevant/required property of the customer, and by invoking some command added to that workspace ViewModel, you could get the current values filled in those (data bound to ViewModel) View elements directly to the customer model.
Consider if you could probably drop the specific customer (and other Model) ViewModels if you refactor things a bit, it would be good practice to keep things from adhering blindly to a certain pattern without explicit cause.
Let's pretend for a second that there is no business model. The only thing you have is a view. If you were to model just that view, without any knowledge of what the data means elsewhere in the system, that is a ViewModel.
The goal of a ViewModel is to, well, model the view it backs. This is a different goal than modeling the idea of a customer in your business domain. To say you will have have one ViewModel per business entity, then, is to say you will have one view per business entity, which leads to run-of-the-mill data-focused UI.
In your particular case, think about the customer edit view. It has fields that correspond to a customer's properties, and thus seems like a natural fit for binding to a customer directly. However, where on the customer object is the "Submit" action modeled? Where is the "Cancel" action modeled? Where is it modeled that field X is an enumerated value selected from a list?
How about the password? If persisted as a binary hashed value, does the view know how to hash its text? What if the system has password strength requirements?
The ViewModel is the mortar between the business model and the UI. It takes concerns from one and translates them into terms of the other. It is the point at which all the above issues are addressed. To say a ViewModel isn't necessary is to ignore its necessity.
You don't need to have a separate ViewModel for Add, you only need a single ViewModel which should do Edit and Add scenarios. If you can delete the record from the edit page than that ViewModel should also have the ability to delete. Your ViewModel should reflect the functionality your View exposes regardless of data.
I think you should reconsider having a single ViewModel for each model. I like to think of ViewModels as normalizing behavior inserted of data. By having a ViewModel for each Model class you will run into architecture issues sooner or later. I look at the application from top down overview, what is my UI trying to accomplish and from there I will get to the ViewModel and eventually I will get to my DataFactory and how the ViewModel maps down to data is almost always not 1 to 1 except for the most simplistic Views. If you try to map 1 to 1 you will have bad UI or your data will not be normalized very well.
The Stack we have here is:
View
ViewModel (Controls everything the user can do in the view, wraps properties from our POCO's)
DataFactory (Maps our POCO's to Entity Framework objects and CRUD)
POCO's (Business Logic, all rules and validation)
Entity Framework (Model, Data Access)
One note here is that ViewModel contains properties from multiple POCO's!
We inject the DataFactory through StructureMap and Unit test with xUnit along with Moq.
To answer you second question I would create a separate view only view to drop in as a user control. But you should still have a CRUD ViewModel in you app that encapsulate all that functionality in a user friendly way.
Thanks.
One reason for this VM abstraction is for testability. Another reason why you want a ViewModel is because it's basically a Data Transfer Object that might be a combination of fields from multiple models in a single container that is more relevant to your current view. Yet another reason to have VM is to take advantage of WPF two ways binding capabilities.
Using your regular model (plain POCO), you can update the View when your model change, but since your model does not implement dependency properties (most likely), you won't be able to take advantage of updating your model when the value in WPF control changes. Which mean you have to manual add a handler and do the copy this value from this control back to the model kind of thing.

Resources