Think of AJAX as Model-View-Controller? - ajax

I think about AJAX in this way:
Model: The server-side where the data is stored and exposed through webservices. In a way this is a model-view-controller within the larger model-view-controller (model = data, view = XML or some other parsable data structure, controller = server-side code that manipulates the data).
View: XHTML/DOM
Controller: Javascript/JQuery
Is this a reasonable way to think about AJAX programming?

You too, huh?
Yes. I think this is a very good way to structure edit operations.
However... You probably want to keep to traditional HTML "view" pages for many documents or objects within an application so that you can support search engines if need be, and so that deep links into pages in your application come up with something meaningful.
This way, using both approaches, you have a hybrid, rather than the "un-webby rectangle" problem where you can never bookmark anything, send links to your friends, or have search engines generate [good] links.
8/10: I guess this also means that you should think of the "server" side of your application as a "REST" service, ideally. Also, be sure not to fall into the trap of thinking the client code is in any way, whatsoever, secure (or even "obscure", for that matter). Make sure the supporting "service calls" back to your web server have a good security infrastructure.

I've been finding it more useful to design ajax code around an event based paradigm. MVC is not mutually exclusive to event based organization but the focus for me has been more and more on the event handling side of things and less on the traditional model view controller way of looking at things.
It's more of a MWE (Model, Widget, Event) organization with the event code taking the place or wrapping the Controller code.

Related

Handling forms with many fields

I have a very large webform that is the center of my Yii web application. The form actually consists of multiple html form elements, many of which are loaded via AJAX as needed.
Because of the form's size and complexity, having multiple save or submit buttons isn't really feasible. I would rather update each field in the database as it is edited by asynchrously AJAXing the new value to the server using jeditable or jeditable-like functionality.
Has anyone done anything like this? In theory I'm thinking I could set up an AJAX endpoint and have each control pass in its name, its new value, and the CRUD operation you want to perform. Then the endpoint can route the request appropriately based on some kind of map and return the product. It just seems like someone has to have solved this problem before and I don't want to waste hours reinventing the wheel.
Your thoughts on architecture/implementation are appreciated, thanks for your time.
In similar situation I decided to use CActiveForm only for easy validation by Yii standarts (it can use Ajax validation), avoiding "required" attribute. And of course to keep logical structure of the form in a good view.
In common you're right. I manually used jQuery to generate AJAX-request (and any other actions) to the controller and process them there as you want.
So you may use CRUD in controller (analyzing parameters in requests) and in your custom jQuery (using group selectors), but you can hardly do it in CActiveForm directly (and it's good: compacting mustn't always beat the logic and structure of models).
Any composite solution with javascript in PHP will affect on flexibility of your non-trivial application.
After sleeping on it last night, I found this post:
jQuery focus/blur on form, not individual inputs
I'm using a modified version of this at the client to update each form via AJAX, instead of updating each field. Each form automatically submits its data after a two seconds of inactivity. The downside is the client might lose some data if their browser crashes, but the benefit is I can mostly use Yii's built-in controller actions and I don't have to write a lot of custom PHP. Since my forms are small, but there are many of them, it seems to be working well so far.
Thanks Alexander for your excellent input and thanks Afnan for your help :)

EmberJS: Good separation of concerns for Models, Stores, Controllers, Views in a rather complex application?

I'm doing a fairly complex emberjs application, and tying it to a backend of APIs.
The API calls are not usually tied to any particular model, but may return objects of various types in different sections of the response, e.g. a call to Events API would return events, but also return media assets and individuals involved in those events.
I've just started with the project, and I'd like to get some expert guidance on how best to separate concerns to have a clean maintainable code base.
The way I am approaching this is:
Models: essentially handle records with their fields, and other computed properties. However, models are not responsible for making requests.
e.g. Individual, Event, Picture, Post etc.
Stores: They are essentially caches. For example, an eventStore would store all events received from the server so far (from possibly different requests) in an array, and also in an hash of events indexed by id.
e.g. individualStore, eventStore etc.
Controllers: They tie to a set of related API calls, e.g. eventsController would be responsible for fetching events or a particular event, or creating a new event etc. They would 'route' the response to different stores for later retrieval. They don't keep the response once it has been sent to stores.
e.g. eventsController, userSearchController etc.
Views: They are tied to a particular view. In general, my application may have several views at different places, e.g. latestEventsView on the Dashboard in addition to having a separate events page.
Templates: are what they are.
Quite often, my templates require to be bound directly to the stores (e.g. peopleView wants to list all the individuals in the individualStore in a list, sorted by some order).
And sometimes, they bind to a computed property
alivePeople: function () { ... }.property('App.individualStore.content.#each'),
The various filtering and sorting options 'chosen' in the view, should return different lists from the store. You can see my last question at what is the right emberjs way to switch between various filtering options?
Who should do this filtering, the view themselves or the stores?
Is this kind of binding across layers okay, or a code smell? Is the separation of concerns good, or am I missing something? Shouldn't controllers be doing something more here? Should my views directly bind to stores?
Any particular special case of MVC more suited to my needs?
Update 17 April 2012
My research goes on, particularly from http://vimeo.com/user7276077/videos and http://jzajpt.github.com/2012/01/17/emberjs-app-architecture.html and http://jzajpt.github.com/2012/01/24/emberjs-app-architecture-data.html
Some issues with my design that I've figured out are:
controllers making requests (stores or models or something else should do it, not controllers)
statecharts are missing -- they are important for view-controller interactions (after sometime you realize your interactions are no more simple)
This is a good example of state charts in action: https://github.com/DominikGuzei/ember-routing-statechart-example
UPDATE 9th JANUARY 2013
Yes, it's been long but this question is lately getting lots of views, and that's why I'd like to edit it so that people may get a sense.
Ember's landscape has changed a lot since this question was framed, and the new guides are much improved. EmberJS has come up with conventions (like Rails) and the MVC is much more well defined now.
Anybody still confused should read all the guides, and watch some videos:
Seattle Ember.js Meetup
At the moment, I'm upgrading my application to Ember.js 1.0.0-pre2.
You should think of your application in terms of states. Have a look at this
Initially, only a route and a template are required to describe
something and finally display it in the browser, that's what the new
API of Emberjs tries to enforce. As your requirements get more
elaborate you can throw in a view, a controller or an object. Each
though answers a specific need.
Consider a view if you need to handle any browser events or wrap
any 3rd party javascript lib you're using for animation, styling ..
Consider an Object if you need to capture domain specific
information, most likely mimics backend information.
A controller is merely a proxy for the domain object and may encapsulate logic that doesn't pertain necessarily to the object.
That's all what's to it. If you learn how to design your application in terms of states, the rest will fall into the right place, providing you're using the latest api, enforcing the rules i mentioned previously.
Since the release of Ember 1.0.0-pre4 with the new router implementation I've seen two good references describing a standardised EmberJS app structure.
Those of you familiar with Rails would find it fairly familiar.
https://github.com/trek/ember-todos-with-build-tools-tests-and-other-modern-conveniences
http://reefpoints.dockyard.com/ember/2013/01/07/building-an-ember-app-with-rails-api-part-1.html
The ember-rails project at https://github.com/emberjs/ember-rails includes a Rails generator for creating an EmberJS application directory structure that is essentially the same as the structure described in the two links above.
The EmberJS guides also now describe the new routing structure. http://emberjs.com/guides/
UPDATE 21/08/2013
If you are using Rails then the ember-rails gem is great. I've used it with a lot of success.
There are two efforts within the ember community to assist in providing a standardised ember application layout. Apparently they are going to be merged but for now check out:
https://github.com/rpflorence/ember-tools
https://github.com/stefanpenner/ember-app-kit
See also this http://addyosmani.com/largescalejavascript/ It is not about EmberJs in particular but it's a great article that gives you an idea how to write larg scale javascript apps.

Wicket and complex Ajax scenarios

When a screen has multiple interacting Ajax controls and you want to control the visibility of components to react to these controls (so that you only display what makes sense in any given situation), calling target.addComponent() manually on everything you want to update is getting cumbersome and isn't very maintainable.
Eventually the web of onClick and onUpdate callbacks can reach a point where adding a new component to the screen is getting much harder than it's supposed to be.
What are the commonly used strategies (or even libraries if such a thing exists) to avoid this build-up of complexity?
Update: Thank you for your answers, I found all of them very useful, but I can only accept one. Sorry.
In Wicket 1.5 there is an event bus. Each component has onEvent(Object payload) method. With component.send() you can broadcast events and each component can check the payload (e.g. UserJoinedEvent object) and decide whether it wants to participate in the current Ajax response. See http://www.wicket-library.com/wicket-examples/events/ for a simple demo.
You could add structural components such as WebMarkupContainers, when you add this to the AjaxTarget everything contained in it will also get updated. This allows you to update groups of components in a single line.
When I'm creating components for a page I tend to add them to component arrays:
Component[] pageComponents = {
new TextField<String>("Field1"),
new TextField<String>("Field2"),
new TextField<String>("Field3")
}
As of Wicket 1.5 the add functions take array parameters [1]. Therefore elements can be added to the page or target like this:
add(pageComponents);
target.add(pageComponents);
Components can then be grouped based on which you want to refresh together.
[1] http://www.jarvana.com/jarvana/view/org/apache/wicket/wicket/1.5-M3/wicket-1.5-M3-javadoc.jar!/org/apache/wicket/ajax/AjaxRequestTarget.html
Well, of how many components do we speak here? Ten? Twenty? Hundreds?
For up to twenty or about this you can have a state controller which controls which components should be shown. This controller sets the visible field of a components model and you do always add all components to your requests which are handled by the controller. The components ajax events you simply redirect to the controller handle method.
For really large numbers of components which have a too heavy payload for a good performance you could use javascript libraries like jQuery to do the show and hide things by the client.
I currently use some sort of modified Observer-Pattern to simulate an event-bus in Wicket 1.4.
My Pages act as an observable observer since my components don't know each other and are reused in different combinations across multiple pages. Whenever one component receives an Ajax-event that could affect other components as well, it calls a method on it's page with an event-object and the ajax-target. The page calls a similar method on all components which have registered themselves for this kind of event and each component can decide, on the base of the supplied event-object if and how it has to react and can attach itself to the target.
The same can be archived by using the wicket visitor. I don't know which one is better, but I think that's mainly a matter of taste.

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

in MVC/MVP/MVPC where do you put your business logic?

in the MVC/MVP/MVPC design pattern where do you put your business logic? No, I do not mean the ASP.NET MVC Framework (aka "Tag Soup").
Some people say you should put it in the "Controller" in MVC/MVPC or "Presenter". But, others think it should be part of the Model.
What do you think and why?
This is how I see it:
The controller is for application logic; logic which is specific to how your application wants to interact with the domain of knowledge it pertains to.
The model is for logic that is independent of the application. i.e. logic that is valid in all possible applications of the domain of knowledge it pertains to.
Hence nearly all business rules will be in the model.
I find a useful question to ask myself when I need to decide where to put some logic is "is this always true, or just for the part of the application I am currently coding?"
The way I have my ASP.NET MVC application structure the workflow looks like this:
Controller -> Services -> Repositories
The Services layer above is where all the business logic takes place. If you put your business logic in your Controller layer, you lose the ability to re-use that business logic in other controllers.
I don't believe it belongs in the controller, because once it's embedded there it can't get out.
I think MVC should have another layer injected in-between: a service layer that maps to use cases. It contains business logic, knows about units of work and transactions, and deals with model and persistence objects to accomplish its tasks.
The controller has a reference to the service that it needs to fulfill its use case. It worries about unmarshalling requests into objects the service can deal with, calls the service, and marshals the response to send back to the view.
With this arrangement, the service is usable on its own even without the controller/view pair. It can be a local or remote object, packaged and deployed any way you wish, that the controller deals with.
The controller now becomes bound more closely to the view. After all, the controller you'll use for a desktop is likely to be different than the one for a web app.
I think this design is more service-oriented.
Put your business logic in domain and keep your domain separte. I prefered Presenter -> Command (Message command use NServiceBus) -> Domain (with BC Bounded Context) -> EventStore -> Event handler -> Repository (read model). If logic is not fit in domain then use service layer.
Please read article from Martin fowler, Eric Evan, Greg Young and Udi dahan. They have define very clear picture.
Here is article written by Mark Nijhof : http://elegantcode.com/2009/11/11/cqrs-la-greg-young/
By all means, put it in the model!
Of course some of the user interaction will have to be in the view, that will be related to your app and business logic, but avoid this as much as possible. Ironically following the principle of doing as little as possible as the user is 'working' in your GUI and as much during 'submit' or action requests makes for a better user experience and usability, not the other way around. At least for line-of-business apps.
You can put it in two places. The Controller and in the Presentation layer. By having some of the logic in the Presentation layer, you can limit the number of requests back into the architecture which adds load to the system. Yeah, you have to code twice, but sometimes this is what you need for a responsive user experience.
I kinda like what was said here (http://www.martinhunter.co.nz/articles/MVPC.pdf)
"With MVPC, the presenter component of the MVP model is split into two
components: the presenter (view control logic) and controller (abstract purpose control logic)."

Resources