Inherited Classes and Dynamic Views in PureMVC (AS3) - apache-flex

I was wondering best practices for views of inherited classes in PureMVC in this situation:
Multiple classes inherit a BaseClass (lets say InheritedClass1 and InheritedClass2)
Each InheritedClass has a respective view (derived from a base view class, but each unique)
With a given dataset (lets say ArrayCollection of InheritedClass1/2 Objects), the respective views need to be dynamically loaded.
The dataset is relatively large, so a TileList would be nice (since it only instantiates objects which are currently displayed)
I can think of a couple solutions, but I find them to be too "hackish" to be the best solution:
In View: Repeater over a BaseClassView which attributes a view to a State (set to the "InheritedClass1" state to add a InheritedClass1 object)
Pros: No unneeded memory increase (States' objects are instantiated when needed)
Cons: View is dependent on the data types, so adds coupling
In Mediator: Loop over the ArrayCollection and addChild() the views based on data type
Pros: Works.
Cons: Mediator is adding things to the View, which defeats the point of the separation of Mediator and View. Slower than a Repeater.
Any comments or other suggestions would be appreciated. Thanks!

The answer is simple if you like the first example. Why not have a map (Object()) on the mediator that assigns datatype to view component (or states). e.g.:
private static var map:Object = {"ic_oneType": "ic_oneState",
"ic_twoType": "ic_twoState"}
And the mediator can assign that map to the BaseClassView.
I'm likely to agree with the idea that you need some form of viewProxy that renders all your inherited views based on data fed to it from the mediator (e.g., first example). Can confirm or deny whether states is the best course of action in your UI though without more concrete examples.

Mediators are part of the View. How would you separate them from the View is beyond me.
I'd got with option 2.
Here's a topic from the pureMVC forum: Dynamically adding View components: where should I do it?.
The post by "pureMVC" should be of interest to you.
Also, the size of the dataset can be problematic. If it's really large you should consider using a List with renderers instead of adding a component for each item (repeaters do that). Which would further complicate things a bit because you'll have to wrap your data to keep the main component decoupled of the Model.

Cons: View is dependent on the data
types, so adds coupling
Typically, a view component has no other purpose than to display the domain data and possibly allow the user to interact with it. It is a given that the view component will need to have some understanding of the domain data.
So feeding a collection of VOs to your view component doesn't add a 'bad' coupling. A 'bad' coupling is when the view component knows about how to reach into the Model tier and manipulate the Proxy that holds the data. Or when the Proxies in the Model tier know how to get their hands on the view components or their Mediators to poke data into them.
Mediator is adding things to the View,
which defeats the point of the
separation of Mediator and View.
As Coded Signal pointed out, we're not trying to separate the Mediator from the View component. The Mediator is the one actor in the PureMVC system that should know the view component, and mediate the communications between it and the rest of the system. The Mediator is the most critical actor in the system with regard to loosening the coupling between the View tier and the Model tier.
To communicate with the view component, other actors send notifications, which the Mediator hears and responds to by manipulating the view component's exposed API; spoonfeeding it data or invoking methods on it. This effectively keeps the rest of the app from needing to know anything about the component.
The Mediator also listens to the component for events and acts on its behalf, retrieving data from the Model tier, or sending notes to to other Mediators or to trigger Commands in the Controller tier. This keeps the component from having to know anything about the system it is connected to. It simply exposes an API of properties and methods, encapsulates its own behavior and sends events when things happen that the system should know about.
So together, the Mediators and View components make up the View Tier of the application.
-=Cliff>

Cons: Mediator is adding things to the View, which defeats the point of the separation of Mediator and View
Not really: they're what the documentation refers to as a collaboration pair and should be treated as such.

Related

Why use ViewBag instead of Application["x"] in View?

I see references to "best practice", but why is it better to use a ViewBag object versus an Application object when accessing static data in the view?
Both are possible. Suppose you want to add an object to every view but not necessarily pass it to view the model (since there may not even be a model for a given view)?
This could be done several ways, like with a global filter, but accessing an application variable is much more convenient.
Both are nasty workarounds that bypass everything that MVC stands for.
In the Model-View-Controller pattern, your Controller prepares a Model containing all values necessary to populate the View, and the View in turn displays the Model properties the way it's intended to.
Any way you use to circumvent that pattern, like ViewBag, Session or Application variables, are anti-patterns that defeat the MVC way - as long as you access those variables directly from the View.
See also Pass data to layout that are common to all pages and Create ViewModel for Navigation: if you need certain values on all pages, consider using a base viewmodel or partial views.
And yes, this discussion borders on pragmatic/purist. If you for example have a menu that's the same for every user, but which is loaded from a database, then sure, go ahead and store it in an Application variable for caching purposes to load it once per AppDomain. But then still use a base ViewModel or Partial to render that menu.
I wouldn't say putting data in a view bag is a best practice. I would say using a view model is a best practice.
Suppose you want to add object to every view but not necessarily pass
it to view the model (since there may not even be a model for a given
view).
Even if you haven't define a view model, conceptually there is a model is you are passing data to the view.
See Why do we use ViewModels?
If the data is on every view, you could create a base view model that every model inherits from that contains the universal data.
you could also create a partial view with its own view model that is then applied to each page.
Normally I design ViewModels taking in consideration the business or functional concepts of the application.
For example, if you are displaying an invoice, the view model should contain all the properties related to invoices that needs to be displayed on that specific view. I wouldn't use ViewBags/ViewData for this purposes.
On the ViewBag I normally put other and "more ancillary" properties like, for example, a boolean for showing/hiding some part of the view, or maybe for some other "not business relevant" properties.
Of course some people could disagree with this and would put everything on the Viewmodels, some others not. This is a decision you must take at the beginning so you can be consistent in the way you design across the application.

MVC Development Best Practice to represent database object and page model objects

I have MVC 3 web app where I get record(s) from DB which is used to render page elements and populate different partial views.
I have classes that represent these DB objects (service layer).
I have also separate set of classes which holds models get returned by the controllers to the view(s).
In my controller, I query DB that returns object to represent DB record.
Then I transfer (MAP) that DB Object to object that Represent the model used by the view(s)
These classes are big and I have to write lots of code in the controller to map.
In most cases I only have some properties which are different.
It seems lots of extra work to do this mapping & lots of code to do the mapping
That is why I am asking.
Is this the correct design approach of developing in MVC framework?
If no, then do you have some pointers that outline the best practice on this aspect.
The Model or ViewModel should only contain information that is used by the View. In some cases, this can be almost identical to what the objects you get from the database are,but this is not always the case. Keeping these concerns separate is good for a number of reasons beyond the scope of a stackoverflow answer. On a side note, I hope you have a separate data access layer and am not querying the database , entity framework or service directly from the controller, again, just to keep those concerns separate.
You can use AutoMapper to map between your DB objects and view models automatically.
Example:
SomeViewModel model = Mapper.Map<SomeViewModel>(someDbObj);
Getting started guide.

ASP.NET MVC3 - Multiple Stored procedures on Single Page

Is it possible to call multiple stored procedures (not multiple result sets from a procedure) and display results on a single page in ASP.NET MVC 3 application?
From what I understand only one Model can created on any single page and my stored procedure is already tied to that Model. I would like to call another procedure and display that result as well on my page
I think the root problem is to understand the meaning of the Model in the MVC pattern.
First of all,
The model consists of application data and business rules, and the controller mediates input, converting it to commands for the model or view.[3] A view can be any output representation of data, such as a chart or a diagram
source
In ASP.Net MVC you link a model to your view, this model should not be part of your domain logic or any domain object
The real model (using the meaning of the MVC pattern) is represented by your domain objects.
So what should you put inside the object that you link to your view??
These objects should contain a representation of the view, in other words simple DTO's containing only the data that is going to be used in the view and nothing more. These models should represent the data being used in the view. If you follow this approach, and you need to display more data in the page, you only need to add another property to this model and voila, you can use it from your view.
In a CQRS architecture, these DTO's should be populated by the Query repositories.
If you do not have a CQRS architecture, just populate these objects in your domain, repositories, etc. Do not do it inside the controller, keep your controllers clean and simple, by making calls to your real domain using services or repositories
Try to avoid the reuse of these DTO's, they should belong to one view only. And do yourself a favor and do not try to reuse a domain object instead of a DTO just to use it as the model.
Following this approach your view-models will be clean, since they will be only DTO's and only containing the data needed by the view. And you can fill these DTO's from different sources, even from different databases if you want.
When you want to perform an action you would read from the model the data provided by the user, and with this data you would call your domain through repositories, services or in a CQRS arc. using commands
The simple answer to your question is "yes".
I suggest you do some more research (ie reading articles and looking at sample apps) into MVC and concentrate on understanding these points:
The Model is a class used to group the data you want to display in the View. It can be populated by a variety of methods and does not have to be the domain object or the pure representation of the database result.
A "page" (the concept of what a user sees in their browser window) can be made up from one or more Views. Each View can be responsible for displaying one type of Model allowing for reuse, but a "page" can have multiple Views.
Models are not "tied" to stored procedures. Perhaps you are using an ORM tool that returns a DTO class (which you call model)? This doesn't have to be the Model used by the View. The Controller could compose several of these DTO classes into one Model class.
N-tier application design where database access is separated from the display logic. MVC tries to encourage this but it still has to be done correctly to avoid tying yourself in knots.
Good luck!

observable pattern on client side

Is there any work around for client side data binding in mvc. I'm looking for something like implementing a observable pattern on client side somehow?
Take a look at knockout it might provide something like what you are after
From their site
Declarative Bindings Easily associate DOM elements with model data using a concise, readable syntax
Automatic UI Refresh When your data model's state changes, your UI updates automatically
Dependency Tracking Implicitly set up chains of relationships between model data, to transform and combine it
Templating Quickly generate sophisticated, nested UIs as a function of your model data
Also
Knockout is a JavaScript library that helps you to create rich,
responsive display and editor user interfaces with a clean underlying
data model. Any time you have sections of UI that update dynamically
(e.g., changing depending on the user’s actions or when an external
data source changes), KO can help you implement it more simply and
maintainably.
Headline features:
Elegant dependency tracking - automatically updates the right parts of
your UI whenever your data model changes. Declarative bindings - a
simple and obvious way to connect parts of your UI to your data model.
You can construct a complex dynamic UIs easily using arbitrarily
nested binding contexts. Trivially extensible - implement custom
behaviors as new declarative bindings for easy reuse in just a few
lines of code.
In order to prevent some of the additional work in creating viewmodels if you already have JSON objects being returned to the client you could use the Knockout Mapping plugin:
Knockout is designed to allow you to use arbitrary JavaScript objects
as view models. As long as some of your view model’s properties are
observables, you can use KO to bind to them to your UI, and the UI
will be updated automatically whenever the observable properties
change.
Most applications need to fetch data from a backend server. Since the
server doesn’t have any concept of observables, it will just supply a
plain JavaScript object (usually serialized as JSON). The mapping
plugin gives you a straightforward way to map that plain JavaScript
object into a view model with the appropriate observables. This is an
alternative to manually writing your own JavaScript code that
constructs a view model based on some data you’ve fetched from the
server.
There are also other frameworks that do similar things like:
Backbone.js
More alternatives here
If you want to implement it without using a "big" framework maybe take a look at this:
https://stackoverflow.com/questions/1005300/example-of-javascript-observer-pattern

Where do you put program scope variables in UI driven application?

Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program.
I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?
I'm just wondering what others do to organize their programs without breaking the rules?
I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.
The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.
The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.
A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .
Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.
Place your singleton in the theApp
class CsolverApp : public CWinApp
{
public:
cData theData;
…
Now to access this from anywhere in your code
#include “solver.h”
theApp.theData.somepublicmethod();
It does make sense to look at this from the MVC (Model - View - Controller) viewpoint. (That the naming of MFC is an homage to MVC is another sick joke on Microsoft's part; it is hard and unintuitive (but by no means impossible) to manage the types of abstractions that are necessary in "true" MVC within MFC.)
Specifically, it sounds like you've thought out the basis for MVC design; you have the classes that do the underlying business logic work (the Model), and you know they should be separated from the UI components (the View). The issue that comes in now is the third part of the MVC trinity; the Controller.
MFC makes this stuff tough by apparently purposefully obfuscating the MVC process, by making you start with a Dialog. In your instance, the Dialog that MFC is starting you off with should be the Controller, and NOT the View. What your Dialog (Controller) is doing for you is managing your UI components (View) and allowing them to interact with your "work" classes (Model). What makes this tough again is that your UI components, to be visible, most likely need to be attached to your Dialog to be visible.
To get this sort of thing right, you really have to basically implement your Controller as a high-level object that gets instantiated from your Dialog; your Dialog is where the initial control flow comes in, your Controller gets control flow, and from there, it should treat the Dialog as just another UI component (albeit one with special status).
This allows you to have the proper level of encapsulation; your Controller invokes your business logic (Model) classes, which can communicate with each other or with the Controller as appropriate; they are segregated from the View by the Controller, instead of being embedded in the UI components and (likely) taking the "easy way" of over-privileged access to UI elements ("Hmm, I need this object to get some input from the user; I could refactor, but it'll be so much easier to just throw a dialog box up, since I have the top-level window handle...").
Once your Controller object is the home to all of the business logic objects, things become easier; you can use the Controller to provide cross-object access for any objects that need other objects. Think about which classes need to be Singletons, and use them sparingly. Resources that need contention management (such as hardware resources) are great examples of "natural singletons"; things which lend themselves to a singleton approach. You may also choose to make your Controller a singleton; depending on the requirements for access to it. Specifically, in your Dependency Injection scenario, the Controller is where you'd instantiate the objects and manage the dependencies.
This is the basic MVC approach; but, like I say, MFC makes it unusually hard and unintuitive, because of the fundamental design of MFC. I learned MUCH more about MVC AFTER an initial VERY negative impression about it due to MFC; if you can, I recommend looking into what MVC implementations look like in other languages.
Good luck!
If I am understanding you correctly, it sounds like the lifetime of your dialog objects is too long. Rather than maintaining the dialogs for the duration of your program, you should consider creating and destroying them as they are needed.
Also, global variables (or singletons) are OK so long as the thing that the variable represents is truly a global thing that persists for the lifetime of the program, rather than just a place-holder for an object of lesser duration. Using globals for the wrong things for simplicity sake will come back to bite you eventually, even if the globals are stored on the main dialog.

Resources