Mimicking objects in javascript - design decision - javascript

I seem to often be making the decision to create objects in javascript that are basically the ModelView or Model objects in an MVC architecture. So when the user changes their properties or whatever via the webpage, the javascript object's properties are changed, and then the javascript object is submitted to the controller. The main reasons I am using this approach are:
Increased flexibility of display.
Alternatively, everything is done
with forms so that I can easily post
them back to the controller. Forms do
not allow various display options
such as wrapping around other
elements and so on.
I am using a lot of javascript
anyway. I have to manipulate the
elements whenever buttons are pressed
(like swapping two list elements
around). I also usually hijack the
buttons and use them with ajax.
The default model binder rarely works
on complex objects so I need to
maintain two sets of objects anyway.
It is easier to perform complex
validation on a javascript object
compared to html.
Are there any libraries or techniques or approach that assist with this approach? Maybe JSON.NET? Do any people try to avoid this approach?

I haven't taken this approach myself but there are some frameworks that sound similar to what you are proposing. The one that looks most interesting is Knockout JS. It provides data binding to your model among other features.

Related

Advantage of using dojo custom widgets over normal javascript function

I am new to Dojo.
My requirement is to form a dynamic table based on json obtained from server,for this kind of use case people are suggesting Dojo's user defined widgets,but i can do this with normal JavaScript function() and i can dynamically apply parsers.
But if i am going for Dojo then what is the advantage?
Well, you can make it easier to re-use and you might even win time. For example: Dojo already has some table-widgets (DataGrid, EnhancedGrid and Sitepen made a custom grid-widget called dgrid).
You can also save time by using a JsonRest store in stead of writing your own AJAX requests to obtain the JSON from the server.
The big advantage of this is that these stores are based upon an API. You can easily switch out your store and choose another store (a Memory store for testing for example). You can also use other widgets with the same store, so if you're unhappy with a DataGrid, you can switch to another widget.
So data/information is seperate from the user interface, which makes the life of a developer much easier.
You can also extend other widgets if you're unhappy with how it behaves, that's all built in in Dojo. By following the Dojo API's you also make sure your widget behaves similar to other widgets, so that will make it easier to use your widget, since it's similar to how other widgets work.
Some interesting URL's:
http://dojotoolkit.org/reference-guide/1.9/dojo/store/JsonRest.html
http://dojofoundation.org/packages/dgrid/
http://dojotoolkit.org/reference-guide/1.9/dojox/grid/DataGrid.html
http://dojotoolkit.org/reference-guide/1.9/dojox/grid/EnhancedGrid.html

Passing Arguments via ajax - Correct Markup

I am putting together a front end for a shopping basket, and it uses a Javascript API to communicate with the database. I have methods such as:
updatePackageQuantity
updateProductQuantity
removePackage
reinstatePackage
Each of the methods require various arguments to be passed, and I'm currently figuring out the best way of retrieving them from the page and passing them.
For example, I currently use classes like this:
Update Quantity
and I'd grab the value from the input field in this instance. I also have 'constants' that I need to pass such as basketID, shopID etc, and I'd like to be able to grab them from the markup somehow.
What would be the ideal way of achieving this? Maybe having a hidden form on the page with a list of inputs, or could I attach the values to attributes, similar to the way its done on twitter bootstrap:
Follow #twbootstrap
I notice they use a lot of attributes prefixed with 'data-'. So what's the right way?
Well..
I believe going with the "data-" attributes would be best, since its a nice little nifty feature of HTML5.
Also, it'll keep your markup clean.
So if you think your application would be running on Modern browsers, this should be the way to go.

Storing data in the DOM

I have a list of books and I want to store data against each book e.g. Price, Quantity, id, catergory id, size, weight etc.
I was looking at storing all this in the dom by extending the li elements representing each book in the list using data- attributes. This data could then be utilised directly with javascript.
However I have read that accessing data- attributes is slow in a performance sense. In addition I can have multiple instances of the same book so am a little concerened about bloat in the html.
An alternative would be to use a JS object to store data for each book.
So my question is what is the best practice for storing data in the frontend, DOM or Javscript?
Thanks in advance
The data- attributes are generally used more as a way to get data into your JavaScript (i.e. From your server-side template), and less a runtime place to store your data. A better place keep your active data is in a JavaScript object, especially if you will be accessing it or manipulating it frequently during the life of your script.
This is more in keeping with an MVC approach, where the data lives in your Model, but may be represented in your View. For this reason, some of the newer MVC frameworks like AngularJS provide automatic two-way binding between the two.
The choice is really dependant on your application architecture and type of functionality in your application. If you are building a single page app I found that using a well constructed json object in conjunction with a good templating plugin gives you much more flexibility in terms of functionality.
I found that indexing your data on an id in your json and then storing that id in the "data-" element gives you a nice way of reacting to browser events (clicks etc) without having to search through JSON structure. Having a JSON structure also makes it a bit easier to do operations such as sorting lists and other global operations that you might want to do without having to rebuild your data from DOM. This method is also better when you work with MVC like frameworks or implement your own "observable" data structures.
On the other hand if you are working with mostly server side code and have only basic functionality in your page that utilizes your "data-" data (such as display book details on click or something simple like that), it is probably simpler to just use the "data-" attribute to store additional details.
The difference between storing that in the DOM elements and keeping data as JavaScript objects is that in the first case you have the data and the DOM element directly related, while in the second case you need to somehow keep similar data and DOM structures in order to keep the data related to the DOM. The second case is, as it sounds, more error prone, because you have to make sure that every change in the DOM is reflected in the data (adding/removing/modifying elements) and every change in the data is reflected in the DOM (adding/removing/modifying data members).
In the case of data-* attributes data is directly accessed from the DOM so the two are already tied together and is, at least in my opinion, a much better practice. However, as mentioned in comments, there is a DOM retrieval overhead which comes with data-* attributes.
In terms of performance both require the data to be stored in memory, be it as DOM element attributes or as JavaScript objects. Retrieving a DOM element attribute is actually more expensive but it's more convenient. Rendering is not affected by data-* attributes as they do not have any functional meaning.

How to properly structure a KnockoutJS application

I am wondering how to structure a KnockoutJS application the right way.
The official documentation almost always uses just one single ViewModel!
After only a few implemented functions my code became very confusing and coming from an object-oriented background I am very allergic to architecture like that. So there must be a better solution.
Being not very experienced with JavaScript I was searching Stackoverflow and found those three options. So I tried the first two options and I am not happy with them:
Having multiple ViewModels like here.
I find it very difficult to decide what DOM-element gets what ViewModel. Also there were several functions called from outside the DOM-element. Maybe I used too little ViewModels with this kind of architecture but communicating between ViewModels seemed to be different and somehow shouldn't be necessary I hope. So how to do that properly?
Having sub views and utilizing the with binding (the second option from those three).
This was my preferred type of architecture because you can have document-wide bindings out of one view model but you can also structure your code into sub-chunks and bind them to wherever you want by using the with binding. This option though requires object literals instead of functions, which are inferior as described in this answer.
I haven't tried method three because it seems a little overkill and also uses object literals.
So is there a method to structure my code and also have full control without using object literals?
I hope this was not too confusing :-P
For any of the options that you mentioned, you do not need to use object literals. The samples just used them to simplify the code. You can choose to create the individual view models in any way that you see fit.
For example in #3, you can use a constructor function like: http://jsfiddle.net/rniemeyer/PctJz/149/. Of course, the actual data would get passed into the function rather than being static. Same with #2, you just would have it wrapped in the "View" object.

How can I write reusable Javascript?

I've started to wrap my functions inside of Objects, e.g.:
var Search = {
carSearch: function(color) {
},
peopleSearch: function(name) {
},
...
}
This helps a lot with readability, but I continue to have issues with reusabilty. To be more specific, the difficulty is in two areas:
Receiving parameters. A lot of times I will have a search screen with multiple input fields and a button that calls the javascript search function. I have to either put a bunch of code in the onclick of the button to retrieve and then martial the values from the input fields into the function call, or I have to hardcode the HTML input field names/IDs so that I can subsequently retrieve them with Javascript. The solution I've settled on for this is to pass the field names/IDs into the function, which it then uses to retrieve the values from the input fields. This is simple but really seems improper.
Returning values. The effect of most Javascript calls tends to be one in which some visual on the screen changes directly, or as a result of another action performed in the call. Reusability is toast when I put these screen-altering effects at the end of a function. For example, after a search is completed I need to display the results on the screen.
How do others handle these issues? Putting my thinking cap on leads me to believe that I need to have an page-specific layer of Javascript between each use in my application and the generic methods I create which are to be used application-wide. Using the previous example, I would have a search button whose onclick calls a myPageSpecificSearchFunction, in which the search field IDs/names are hardcoded, which marshals the parameters and calls the generic search function. The generic function would return data/objects/variables only, and would not directly read from or make any changes to the DOM. The page-specific search function would then receive this data back and alter the DOM appropriately.
Am I on the right path or is there a better pattern to handle the reuse of Javascript objects/methods?
Basic Pattern
In terms of your basic pattern, can I suggest modifying your structure to use the module pattern and named functions:
var Search = (function(){
var pubs = {};
pubs.carSearch = carSearch;
function carSearch(color) {
}
pubs.peopleSearch = peopleSearch;
function peopleSearch(name) {
}
return pubs;
})();
Yes, that looks more complicated, but that's partially because there's no helper function involved. Note that now, every function has a name (your previous functions were anonymous; the properties they were bound to had names, but the functions didn't, which has implications in terms of the display of the call stack in debuggers and such). Using the module pattern also gives you the ability to have completely private functions that only the functions within your Search object can access. (Just declare the functions within the big anonymous function and don't add them to pubs.) More on my rationale for that (with advantages and disadvantages, and why you can't combine the function declaration and property assignment) here.
Retrieving Parameters
One of the functions I really, really like from Prototype is the Form#serialize function, which walks through the form elements and builds a plain object with a property for each field based on the field's name. (Prototype's current – 1.6.1 – implementation has an issue where it doesn't preserve the order of the fields, but it's surprising how rarely that's a problem.) It sounds like you would be well-served by such a thing and they're not hard to build; then your business logic is dealing with objects with properties named according to what they're related to, and has no knowledge of the actual form itself.
Returning Values / Mixing UI and Logic
I tend to think of applications as objects and the connections and interactions between them. So I tend to create:
Objects representing the business model and such, irrespective of interface (although, of course, the business model is almost certainly partially driven by the interface). Those objects are defined in one place, but used both client- and server-side (yes, I use JavaScript server-side), and designed with serialization (via JSON, in my case) in mind so I can send them back and forth easily.
Objects server-side that know how to use those to update the underlying store (since I tend to work on projects with an underlying store), and
Objects client-side that know how to use that information to render to the UI.
(I know, hardly original!) I try to keep the store and rendering objects generic so they mostly work by looking at the public properties of the business objects (which is pretty much all of the properties; I don't use the patterns like Crockford's that let you really hide data, I find them too expensive). Pragmatism means sometimes the store or rendering objects just have to know what they're dealing with, specifically, but I do try to keep things generic where I can.
I started out using the module pattern, but then started doing everything in jQuery plugins. The plugins allow to pass page specific options.
Using jQuery would also let you rethink the way you identify your search terms and find their values. You might consider adding a class to every input, and use that class to avoid specifically naming each input.
Javascript is ridiculously flexible which means that your design is especially important as you can do things in many different ways. This is what probably makes Javascript feel less like lending itself to re-usability.
There are a few different notations for declaring your objects (functions/classes) and then namespacing them. It's important to understand these differences. As mentioned in a comment on here 'namespacing is a breeze' - and is a good place to start.
I wouldn't be able to go far enough in this reply and would only be paraphrasing, so I recommend buying these books:
Pro JavaScript Design Patterns
Pro Javascript techniques

Categories