I'm an assistant in a course where t开发者_运维技巧he students implement a web app (It's a Q&A site similar to stackoverflow) with the help of the Play! framework. This is a Java-based framework that relies on the MVC Pattern. The Model and Controller are written in Java where the view is written in HTML / CSS and some extensions that the framework provides to access informations of the model.
The question that came up recently is how much javascript can be used in the view to change something in the model (e.g. to vote, to comment, etc.) so that the MVC Pattern isn't violated too much. Or should all Javascript functions that actually change data in the model be avoided and instead be routed through the controller? Is there a best practice for this?
Presumably by "javascript" you mean more AJAX? (Rather than JS modification of output... in which case it's just an extension of the view). There's no reason why your AJAX can't/shouldn't be routed through your MVC like any other component.
Of course that may precipitate changes to the original MVC design, but perhaps that's an acceptable part of the course. Of course when using AJAX your view rendering could handled by JS embedded in the existing view - if data's provided as JSON rather than HTML fragments.
How is it possible that JavaScript code, executed on the client, can change "data in the model"? Are you merely changing properties in JavaScript representations of the objects client-side, or are you somehow invoking server-side methods from the JavaScript (i.e. calling into servlets) to change the data?
If it's the latter, then this is a violation of MVC - all requests from the client should go through the controller.
I tend to route all AJAX calls that need to do any CRUD operations to send a GET or POST request to a function in the controller, and let it handle communicating w/ the model.
This is how HTML/CSS views process data(i.e., getting it from the model, via the controller, and sending GET & POST requests to the controller) and since JS is client-side, it shouldn't be treated any differently.
I'm excessively using ajax in my CakePHP MVC app. In this case, the controller actions get only called by javascript, beside one static controller which delivers the html/javascript pages to the browser.
精彩评论