How to use JavaScript MVVM/MVC with pre-loaded data - javascript

I want to load an HTML page with existing data (a list of comments or widgets or whatever), then use Javascript to render additional data in the same format as it is input by users interacting with the page.
I'd like to use a model stored in a JavaScript object that represents both existing data on the page as well as new data from user input, then observe to the model to update the DOM when it changes.
I'd like to render JS templates to display data entered by users quickly, without hitting the server again.
I would like to avoid writing server-side and JavaScript templates that render the same data.
To solve the first problem of building the initial model it seems like the options are, in order of preference:
Use JavaScript to pull the data rendered in HTML to build the initial model, or
Render JSON directly to the DOM and build the JS object from that, or
Hit the server again after the page is loaded as an ajax call to get the data as JSON
To avoid having server-side and client-side templates to display the same thing:
Use use something like Pure to build templates from the DOM, or
Only use JS templates and use one of the second options above to initially render the page (populate them from JSON rendered to the DOM or make an ajax call to get JSON to populate them).
Use a templating system that works on both the server and client.
I feel like none of these solutions are particularly elegant, and I'm curious as to what other patterns I may not have thought of or if there is a common solution.
My environment is Rails 3, but the problems are applicable to any server -> HTML/JS setup. I can see how some of this might be easier with something like Node.js but I'm principally interested in solutions that would apply to Rails.

There's so many ways to accomplish this. I have been struggling with this same issue. I think that once the complexity of your web app reaches a certain threshold you have to resort to javascript to keep the state correct. Jquery (among other dom manipulation frameworks) really help but at a certain point it can become spaghetti code.
I just touched this binding javascript library called Knockout. It's pretty elegant and simple to use it tries to follow the MVVM pattern by allowing you to create a ViewModel with observables that you can bind html elements so that their values and attributes change based on your ViewModel values.
If you're creating dynamic html you can always embed the initial values of the javascript ViewModel along with the html of the page so that you can avoid that initial ajax call.
Out of the box it is compatible with jquery templates which just makes dom manipulation a breeze. I've just started using it and I'm loving it so far.
Hope that helps.

Related

Django saving models by JS rather than form submissions?

I have a contract job for editing a Django application, and Django is not my main framework to use, so I have a question regarding models in it.
The application I am editing has a form that each user can submit, and every single model in the application is edited directly through the form.
From this perspective, it seems every model is directly a form object, I do not see any model fields that I could use for custom variables. Meaning instead of a "string" that I could edit with JS, I only see a TextField where the only way it could be edited is by including it on a form directly.
If I wanted to have some models that were custom variables, meaning I controlled them entirely through JS rather than form submissions, how would I do that in Django?
I know I could, for example, have some "hidden" form objects that I manipulated with JS. But this solution sounds kind of hacky. Is there an intended way that I could go about this?
Thanks!
(Edit: It seems most responses do not know what I am referring to. Basically I want to allow the client to perform some special sorting functions etc, in which case I will need a few additional lists of data. But I do not want these to be visible to the user, and they will be altered exclusively by js.
Regarding the response of SColvin, I understand that the models are a representation of the database, but from how the application I am working on is designed, it looks as if the only way the models are being used is strictly through forms.
For example, every "string" is a "TextField", and lets say we made a string called "myField", the exclusive use of this field would be to use it in templates with the syntax {{ form.myField|attr:"rows:4" }}.
There are absolutely no use of this model outside of the forms. Every place you see it in the application, there is a form object. This is why I was under the impression that is the primary way to edit the data found in the models.
I did the Django tutorial prior to accepting this project but do not remember seeing any way to submit changes to models outside of the forms.
So more specifically what I would like to do in this case: Let's say I wanted to add a string to my models file, and this string will NOT be included/edited on the form. It will be invisible to the user. It will be modified browser-side by some .js functions, and I would like it to be saved along when submitting the rest of the form. What would be the intended method for going about doing this?
If anyone could please guide me to documentation or examples on how to do this, it would be greatly appreciated! )
(Edit2: No responses ever since the first edit? Not sure if this post is not appearing for anyone else. Still looking for an answer!)
There is some terminology confusion here, as SColvin points out; it's really not clear what you mean by "custom variables", and how those relates to models.
However your main confusion seems to be around forms. There is absolutely no requirement to use them: they are just one method of updating models. It is always possible to edit the models directly in code, and the data from that can of course come from Javascript if you want. The tutorial has good coverage of how to update a model from code without using a form.
If you're doing a lot of work via JS though, you probably want to look into the Django Rest Framework, which simplifies the process of converting Django model data to and from JSON to use in your client-side code. Again though DRF isn't doing anything you couldn't do manually in your own code, all without the use of forms.

mvc approach with javascript / jquery no framework

I'm developing a large scale application. Initially my approach was confused , I am a beginner in javascript even if I develop since January.
I was looking for an mvc approach and I found some guide lines, like :
Model : contains AJAX call , and services
Controller: e.g. jQuery widget and so on
View: e.g. rendering of HTML and so on..
I don't really have clearly how to structure a javascript application following perfectly the three above suggestions. I can do everything, I can manage template I can write jQuery manipulation , I can do AJAX call.
What is not clear to me is how to get really divided these three modules. When I try this approach I'm not able to make any module to do only what it has to do.
I tried also an MV* approach which, for what I see and for my needs maybe it's a better approach, because I have to do bind tons of divs , generate events , all by client side, receiving only data from server side.
What I would like to know:
Which are the really competences of each Module?
If, for example, I have to bind a click event to a button , where do I have to write the
.on('click',callback)
method? Where I have to write the callback he's gonna call?
I wrote : no framework because I'm sure that if I don't understand an approach writing it from scratch, its impossibile I will completely understand the use of a complete framework.
I hope that my doubts were clear, if not, please comment, I'll try to explain better if I can.
Sorry for my english in any case.
This is not an answer because there is no one answer. I just want to mention a few do's and don't's.
Do store pure data in the model. Think of it as business objects rather than display objects. For example, money should be stored in the model as a number, probably with some digits after the decimal point, plus an indicator of what currency it is, if that matters. Don't store the number as a string with local choices of the characters to separate the 1000's and the integer part from the fractional part and the right number of digits after the decimal point.
Do put the handler code for the click events (and similar user actions) in the controller.
Do put the code that causes updates the screen on load or on any external event in the controller. (An external event might be something like an update to a stock price due to stock exchange data or an update to the weather report coming into the application.)
Do put the HTML or the code that generates HTML as part of the view.
Do have the controller call the view to get the display updated/changed at the right times.
Do have either the controller or the view call the model to get the current model data values or the update the the current model data. (See similar "don't" below.)
Do reduce the connectivity between the three parts--M, V and C. Define clearly who can talk to whom for what purpose and keep that rule sacred. If you find an exception, its a smell indicating a problem with the big picture of those rules.
And some more things
Don't put the code that displays the screen on load in the controller. That's clearly a view concern. This means the controller has to call into the view somehow.
Don't spaghetti connect the M, V and C code in random fashions. For example, you might make a rule that the model never calls code in the view or controller.
Don't have both the controller and the view talking to the model.
Questions:
Where does the code go that hooks up the event handlers?
Where do you put the "business logic"? This is the code that knows the rules of your application. Validation, for example, is business logic. Some code may need to know how zip codes look for the US and postal codes for the UK or Canada. If the validation fails, the controller is the one that tells the view to show an error message or red mark or vibrating box or whatever. Does the business logic of validation rules also go in the controller?
Where does the code go that loads data from external data sources? (servers, JSON web services, databases, screen scraping, etc.) You might think "model" but then the model has to call into the controller when new data comes back to tell it to update the view. That doesn't seem right.
Similarly, what is the code that handles the equivalent of a "submit" button, moving to another screen.
If converting data from a form that is displayable on the screen to a form that is pure data is too slow, what do you do?
There are always self-contained portions of the screen that can be built with their own MV&C. How do you set up interactions between multiples of those little MVCs and the big MVC that is the whole screen? Are those little guys the views for the big MVC? Or are the controllers? Can they be both at once? Is there a big model with the little models in it or does data flow between little models and big models? Who knows about all this?
Is there an even bigger MVC comprised of multiple screens? It would probably be on the server if it exists.
How do you handle "synthetic" events? This is something like an "event" that occurs when the data was ok but is now in a bad state (or was incomplete and is now complete). Listeners to this event can disable the "Submit" button and display error messages or animations calling the user attention to the problem. It could be anything that isn't a generic event built into the framework or language. Perhaps its a message to the server indicating a change in the state of a multiplayer game's world view.
This is just a list of things that pop to mind when you are writing your own MVC or when evaluating an existing framework.
There is no clear answer outside a specific framework. Although the general responsibilities of the MVC pattern are (almost) clear to everyone, each framework has its own interpretation of exactly what pieces of code to put in each of these layers - some frameworks even skip some layers, or add different ones instead.
I know you don't want to use a framework, but still, it's worth to have an overview of how the current solutions work, so you can make an informed decision if you like the way they work or if you prefer to roll your own.
I recommend you at least take a look at one server side MVC framework (such as Ruby on Rails or Asp.Net MVC) and some client side MVC frameworks too (Backbone.js, Angular.js, etc. - javascript only). Read their documentations, and learn from the choices others have made (and tested). The site todo mvc can help you to compare different client MVC frameworks to find the approach you like better.
This is not a simple topic, and discussing the pros and cons of each approach from scratch can take forever.

Dynamic drop down menus using JavaScript without using a database

Is there a quick and dirty technique of creating dynamic drop down menus without using a database backend? There will be three levels of drop down menus and there are an awful lot of items in them, hence the quick and dirty!
Thanks
The fact that you choose to load the items from a database is pretty much unrelated to the drop-down menu itself. You can always read from a JSON, .csv or xml file. Depending on the implementation, you could even have the items loaded straight into the HTML page (but that would be painfully slow if you have many of them, so not recommended).
Load the file (preferably JSON) containing your items via AJAX, parse it and create the markup dynamically.
It's pretty hard to give details as the source of the contents shouldn't be so important. If you plan to use the classic <select> tag, just create that element. jQuery is your friend for quick and dirty.
Using JSON.parse() will return the structured object which you can use to loop through elements and add children to the <select> node.
Your question is a bit vague, so I'll give you a "general" answer.
There are tools like jQuery and knockoutJS out there. You could use knockoutJS to represent a client side view model and use it ( maybe combined with jQuery ) to populate the view with your data.
I think you should take a look at knockoutJS and especially observables, observable arrays, the options binding, and its support for AJAX requests - that sounds like a reasonable place to start.
The knockoutJS documentation can be found here: http://knockoutjs.com/documentation/introduction.html

Embedding JavaScript into an AJAX partial response

Is it considered bad practice to embed javascript into partials returned via AJAX?
Let's say that on http://mysite.com, I have a button that gets a form via AJAX.
Now let's say that I want to add some javascript event handlers to this form using jQuery (for validation and such).
The current ways to do this seem to be:
In the AJAX callback that returns form, I can setup event handlers
for the tag.
I don't like this approach because it puts code that controls my form in two places: in the partial being rendered, and in the global javascript file(s) being included.
Instead of returning a form from the server side, do everything client side. When a response from the server is required (for example, to validate the form), return JSON from the server, and create the resulting HTML elements (things like error messages) in JavaScript.
Now this approach makes me feel as though, I'm using JavaScript to create HTML elements instead of using more powerful server side tools (template languages) to do it.
I feel like the solution involves embedding JavaScript code into the HTML returned by the AJAX partial, so that it's an independently functional component of my application, and all the code is in one place.
Is there a cleaner way of doing what I'm trying to do here?
I'm not sure the argument can be made today that javascript is somehow inferior in terms of "power" when compared to other back-end languages... I think maybe because today javascript is a valid back-end language?
I think the second option makes sense because you're containing client/interface code, and segregating server-side logic for data manipulation and presentation.
There are plenty of javascript template libraries that work very well in my opinion, that is if you don't want to go the full javascript MVC route.

jQuery: Templating data

I have a unique situation where I'm building a site that will call data via AJAX and load it into "containers" (basically just divs styled and arranged according to elements retrieved from the AJAX callback).
I'm not sure how many of these unique container types will be created (styled and rendered) when all is said and done, so I'm looking for a solution that will allow me to store containers in a separate file(s), load them dynamically as they are needed, populate the content, and rendered them on page.
I'm not sure if I should write my own loading/template solution or use an existing JavaScript template engine (e.g.: Pure).
The reason I'm hesitant to use an existing JavaScript template solution is they all seem focused on binding and looping on existing page elements, whereas I'm more concerned with the ability to load-up and binding to dynamic content.
You might want to give jQote a try, it's the most powerful jQuery templating engine as it let's you use scripting inside your templates.
Go check it out, it'll suit your needs, I promise.
http://aefxx.com/jquery-plugins/jqote
After starting with JST, we moved to EJS:
http://embeddedjs.com/
It's more powerful, syntactically simpler, and you can put your templates in different files.
The website is pretty nice too.
I found http://code.google.com/p/trimpath/wiki/JavaScriptTemplates pretty useful for this.
I am planning to use jTemplates for a future project that will need to do something like this, it is very fast and has a nice jQuery plugin

Categories

Resources