How do you design a text-based view using Ember.js or some other MVC javascript framework? - model-view-controller

I have an homemade javascript which, among other things, do some kind of text-formatting work in order to emulate a retro text-based game:
When developing it, i tried to stick close to an MVC model, and this is what i did:
The data model basically consists of a list of objects mapping strings to very specific locations in the display, like this
[{
"value":"Hello!",
"color":"blue",
"row":1,
"column":13
},
{
"value":"What is your quest ?",
"color":"red",
"row":5,
"column":10
},
/* ... some other data */]
Then my view consists of a simple <pre> tag. When my controller draws the model on the view, it iterates through each string-location pair and create a <span> for each one that is appended to the <pre> tag. To keep the formatting consistent, it also adds "blanck" span each time it is needed.
<pre>
<span> </span><span class="blue">Hello!</span><span> </span><br>
<!-- ... other lines of the scene-->
</pre>
It's pretty simple, but it worked great until i had to dynamically change a span text value, without redrawing the whole scene each time.
So i took a look on the internet and realized that Ember.js existed, it really seems to be exactly what i could use to improve my whole code.
Now, i tried to redesign it using Ember.js, but as i don't fully understand yet its features i ran into a problem:
How do you represent a 'text-based' view into an Ember.js handlebar template ?
What am i missing here?
My data model contains both the value and the position in the display, so i don't exactly see how handlebars template could fit my needs. Or perhaps dynamically generating the template is an option ?
What do you think ?
Am I choosing the wrong framework or misunderstanding its use? is it my original MVC design that is wrong ? Changing the data model for something completely different is not an option i can easily consider as it would impact everything.
Do you have any ideas on how this could be implemented using Ember or some other framework?
Any advice will be appreciated :)

I made a rudimentary example on jsfiddle on how you could use ember for this.
Each row is an object and we have an ArrayProxy holding such objects. Thus if we have 10 rows, we have 10 row objects.
The view is binding one output line per row object.
Enjoy the flying bird:
http://jsfiddle.net/algesten/YMrW3/2/
Edit: Better to {{#if}} away empty rows as pointed out by ud3323:
http://jsfiddle.net/ud3323/92b24/

Related

What is the right method to add text areas to Django?

I have written python code that analyses two text sources and compares them.
I'd like to implement this dynamically via two text boxes that a user could either type into or manually upload. I have already begun coding this using HTML. Would it be better to implement a widget or the models instead to make the text area boxes?
Edit:
I wrote this question when I was just figuring Django out, so forgive me if it sounds confusing. But everyone starts somewhere. I'm unable to delete the question as contributions have been made already. YouTube courses proved helpful in learning the basics, if any beginners stumble upon this.
You use a form object. Django has form objects (https://docs.djangoproject.com/en/2.0/topics/forms) that take a model and translate it into html elements. So I guess in a way, you implement the model but I want to stress that that's not actually what's happening from a technical standpoint. A better way to say it is that you're implementing forms. The reason I stress this so much is so that you understand what's really going on so that you don't have misunderstandings that end up costing you in code clarity and readability.
So to answer your question, you can implement django forms to do this very easily. The way you implement it depends on your models and how they are designed since the forms use the models to create the right html form elements. If you're dealing with one model that will be instantiated by the form input, create a model form. This will take the input from the form and create your model instance. If you're dealing with one form that uses multiple models, then use a generic form. In this case, you will have to write your own save method that does the actual logic of the form.
One other thing to add... No matter what, your end result will always be a widget on the HTML in the end. Django forms translate a model class into a form element with input elements. If you didn't use Django forms, you would still do the translating, but you would have to do it from scratch.
I hope this helps and that I correctly understood your question.

Durandal and multiple views using the same vm

I have an ADD and an EDIT page for a customer entity. The data to support each function is similar, however there are business rules that differ between the 2, and slightly different UI, so my original thinking is that I make 2 separate views, but use a single vm. This is a different approach than the John Papa example I'm using as my guide, as he had a separate vm for each. (sessionadd.js, sessiondetail.js). The data is identical so it seems like a lot of duplication, but maybe that's the way to go.
Two questions: what is the best practice in this scenario where the data for an add/edit is the same, but the rules are different? I can already see myself doing "if (mode == 'add'){ // stuff } else {// its an edit }. That bothers me a little, but I also don't like the idea of having to change 2 vms if I add a new field to the views.
Second question, can I specify the view as part of the route definition? I didn't see anything in the docs but I'm still new to the framework. In the following routes, I would like the first one to be loaded with custedit.html and in the second one custadd.html. Both using the custmaint.js vm (never at the same time tho).
{ route: 'custedit', moduleId: 'viewmodels/custmaint', title: 'Edit' },
{ route: 'custadd', moduleId: 'viewmodels/custmaint', title: 'Add' },
thanks
You can customize the view you want to be used by defining getView() or viewUrl() on your viewmodel as described here:
http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks.html
As to your initial question, if they are very similar, I would definitely combine edit and add operations within a single viewmodel and single view. Sharing the same viewmodel but splitting the views will likely result in a ton of duplicated view code. You could always decompose the elements of your view into smaller views if you need to simplify.
If the edit and add experience are different enough to warrant a separate view, I would create a separate viewmodel as well (and potentially look into splitting view parts and viewmodel functionality into smaller components)

Combining Require.js, Backbone.js and a server side MVC framework

We're actually planning a really complex web application. At least for my own standards.
In the past we have always been using a combination of a server side MVC Framework (Codeigniter) and client side functionality (jQuery and plugins). We have simply written inline javascript code in our views. This worked as expected, but of course with several disadvantages:
no caching
duplicated js code
maintainability issues
...
My main goal now is to organize the client side code in an efficient and easily maintainable way. But I want to stay with the server side MVC because of the existing know how and some existing interfaces. Furthermore I want to reduce complex DOM manipulation with jQuery and "spaghetti code".
Now I thought about a combination of Backbone.js and Require.js but I really can't find a tutorial or any solid description about how to combine them with a server side MVC.
Is it even recommended?
In my old apps I got a file structure like this:
application (CodeIgniter)
assets
js
css
imgs
Are there any ideas or best practices?
Thank you!
To add to mexique1's advice, it might be worth looking at the backbone-boilerplate project. It should provide you best-practice solutions for many of the problems you're currently considering, such as the combination of require and backbone, the organisation of the client-side of your project, and the reduction of complex DOM manipulation (see templating).
The challenge, as you anticipate, will most likely be in combining the boilerplate approach with the approach you're used to. However, it will almost certainly be worth the effort since it should provide you a solid foundation for this and future projects.
I think Backbone is a good choice, and Require is not mandatory here.
Require will just help you organize your source code and maybe improve performance. I think you can start right away with Backbone, which will be the thing you are going to use most, and add Require later.
Regarding Backbone, yes it's easy to use to use its Model with an existing MVC application, provided it returns JSON. To load your existing data you will want to use the fetch method combined to url to adapt to your existing code, or your own method.
Generally, think about which models are displayed in which views. Backbone helps you think this way : I'm displaying Models represented as JSON data in Views which are made by HTML.
Also, for the view layer, it's very easy to reuse your existing HTML, because views are not tied to anything, no JavaScript templating or nothing.
Simple example :
<div id="user">
<span class="name">John</span>
</div>
var UserView = Backbone.View.extend({
render: function() {
this.$el('.name').html(this.model.get('name'));
}
});
var userView = new UserView({el: $('#user')[0], model: ...});
In this example the #user div reflects the state of a User model, with its name.
Also check the Todo App example in Backbone.

Spring Views - Combining elements into views

Currently, in our deployment we have a abstract type Component which represents a part of our Page, basically an element such as a Question, which can have multiple choice, a text box or any other form of answering it, or a Video that users can play, basically a shard of a page that is interchangeable, basically, our design was to have a specific area in our website which would be rendered through a list of Components, we tried at first to have each "Page" object have a List of Components, and each Component would have a method render that would return a Spring View, we thought we could iterate over the list and somehow mash the views together.
We also tried using XSTLViews with no more success, it seems to be more of a design problem and our abuse of the way Spring MVC should be used.
We will really be glad to receive any advice/tips/corrections about how to do it right and maybe some corrections about misconceptions we might have.
It sounds like you're more than half way to a design that uses AJAX to build your page. You're trying to mash up a bunch of Components into one request. What if you returned a container page which then requested/inserted a block of html for each URL it was given a render time. Each of these URLs would refer to a single component. It might be a performance hit if you are including a lot of these Components, but it seems to fit the design.

Reload the page without submitting it back to the server

the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.
My original code is written in jsp/struts and I have sort of achieved this by using
onchange="javascript:submit()" to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.
I also have other problems with the serverside validation due to this method.
Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.
I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.
AJAX is your only other option my friend, unless on the original page load you load all the other possible values of the Text Box so you don't need to go back to the database. Well, you could try putting the text box in an IFRAME, but you will probably run into more problems with that approach than just going with AJAX.
Without AJAX what you are asking is going to be difficult. Another option (which is ugly) is to write out all possible values for the second list box into a data structure like an array or dictionary.
Then write some javascript to get the values from the data structure when the user selects from the first list box. The amount of javascript you will have to write to get this done and to do it correctly in a cross browser way will be much more difficult than simply using AJAX.
Not sure why you'd try to avoid AJAX in today's world, the JS libraries out there today make it so simple it's crazy not to try it out.
I just had to replace a page that was written as Vincent pointed out. I assume at the time it made sense for the app, given the relative size of the data 4 years ago. Now that the app has scaled though, the page was taking upwards of 30 seconds to parse the data structures repeatedly (poorly written JS? maybe).
I replaced all the logic with a very simple AJAX call to a servlet that simply returns a JSON response of values for the 2nd drop down based on what was passed to it and the response is basically instant.
Good luck to ya.
One way is to change the form's action so that you submit the form to a different url than the "save" url. This lets you reload certain aspects of the form and return to the form itself, instead of committing the data.
<script>
function reload() {
document.forms[0].action="reloadFormData.jsp";
document.forms[0].submit();
}
</script>
<form action="saveData.jsp" method="post">
<select id="A" name="B" onchange="reload()"><!-- blah --></select>
<select id="B" name="B"><!-- blah B --></select>
<input type="submit">
</form>
If I understand you correctly, that you want either a dropdown (<select>) or a textfield (<input type="text">) depending on a choice (typically a checkbox or radiobuttons) somewhere above in a form?
I that case you may need to handle the two types of input differently on the server anyway, so why not have both the selectbox and textfield in the area of the form with different names and id and one of them hidden (display = none). Then toggle visibility when the choice changes. On the server you pick eiter the selectbox or textarea input (wich will both be present unless you disable (disabled="disabled") them too, wich I think is uneccesary) depending on the choice input.
Of course if you expect that the user usually just need the text-input, and a few times only, needing a massive list; it would be better to use ajax to retrieve the list. But if it's the other way around (you need the text-field only occationally), as I assumed above, it will be faster to have both present in the initial form.
If the drop down only contain easily generateable data, like years from now to houndreds of years back it could even be much faster (requiring less bandwidth on the server) to generate the data client side using a for loop in Javascript.
I know a taglib that can fit to your problem:
AjaxTags.
I use this taglib in my J2EE projects and it is very simple to integrate it into web applications.
This taglib give you several tags designed to execute AJAX request in your jsp files.
Here is the description of each tags: http://ajaxtags.sourceforge.net/usage.html
The tag which will help you is the ajax:select tag. It allows you to populate a select tag which depends on an other field without reloading the entire jsp page.
If you more informations about it, ask me and i'll try to answer quicky.
Along the lines of what Strindhaug said, but if you need dynamic data:
Could you have the backend write JS into the page, and then the JS would change the form as required? The backend could propagate some variables for descriptions and such, and then the JS could change/update the form accordingly. If you aren't familiar with this, libs like jQuery make things like this easier and more cross-browser than rolling-your-own (at least in my experience).
Aside:
If you're not using AJAX because it was hard to code (as I didn't for a while because my first experience was from scratch and wasn't pretty), as others have said, libs like MooTools and such make it really easy now. Also, there is not shame in using AJAX properly. It has a bad rap because people do stupid things with it, but if you can't simply write premade values into the form or you have to do live look ups, this is one of AJAX's proper uses.

Resources