Difference between programmatically vs declaratively created widgets in dojo? - javascript

I know in dojo we can create any widgets in two ways,
programmatically
declaratively
To create widgets programmatically we'll use JavaScript, whereas for declaratively we'll use dojo attributes in HTML tags.
Can someone explain me what are the differences between them?
which one is mostly preferred and why?

Difference
Well, there are certain differences between both ways. In the declarative way, all configuration is based upon HTML attributes like dojo-data-props but also some other attributes like the value, title, ... . So the DOM node you create actually serves as some kind of placeholder.
When you create widgets by writing JavaScript code, you will have to provide the DOM node you will attach it too, but the biggest difference is that it will not copy the HTML attributes from that DOM node. The DOM node here only serves as a container, not a placeholder.
Preferred
There is no solution that is mostly preferred and it usually depends on the requirements of your application and what you think is the cleanest way of developing.
Personally I like the declarative markup because in the end it's a part of the user interface. However, you can go as far as you want. I've seen people creating stores and widget event handlers in a declarative way too, but I personally prefer to write them in JavaScript since they're not a part of the user interface.
There are also other reasons that might change the way you would create widgets. For example, one of the biggest drawbacks of declarative markup is that you need to parse the page (for example with parseOnLoad). This usually is slower than creating the widgets programmatically. You can improve it by only parsing certain DOM nodes, but then you have to write additional code (and it still isn't faster).
Just a small note; this doesn't mean that the declarative way is slow. It's just an extra operation that should be executed and thus, it's a bit slower but chances are that the end user will not even see the difference.
An advantage of the declarative way however is that, when loading the page, the end user is able to see the placeholder. If you pick the right placeholder (for example, a <select> for dijit/form/FilteringSelect and dijit/form/ComboBox), the end user will at least see something. If you create everything programmatically, the end user will see a blank page until the JavaScript code is executed.
So if performance is one of the requirements, then you could choose creating them programatically. If you like to have seperation of code where the presentation layer is seperated from the business logic, then I would recommend using the declarative way.
But in the end, both solutions are good.

Related

Should I use Javascript when dealing with many similar pieces of HTML code?

Right now I have a hard-ish to read HTML page composed of ~300 lines of code. Most of the code however comes from the same form repeated multiple times, with no changes whatsoever except for the id (which differs by a number). Would it be an acceptable or even encouraged practice to use Javascript to attach the same piece of HTML code to the DOM as many times as I need it? I'm a beginner to JS, so I don't have any clue about any performance impact that this could cause, and I can't see anything bad coming from this approach.
In my opinion, semantic HTML that is verbose and not rendered through JavaScript is the way to go. The only reason you wouldn't want to do this is if your application could scale and more forms would be rendered in the future. If there are a set amount of forms, debugging and handling data will be easiest by simply hardcoding all of the HTML.

Declarative or programatic approach in DOJO?

While creating DOJO Components when should we prefer declarative approach and programatic approach?
Depends entirely on your needs and preferences. If you have designers rather than programmers needing to add Dojo widgets, it may be preferable for them to use the declarative markup. However, if you insist that the HTML markup pass w3c validation, you'll want to use the programmatic approach instead.
I prefer the programmatic approach because it allows me to wrap an entire form as a javascript object and create methods to instantiate and validate its widgets. Addendum after comment: I will usually create a javascript object with its form inputs and dojo/dijit widgets as its properties so I can refer to them as this.startDateTextBox, this.titleInlineEditor etc. I handle the instantiation of the dojo widgets in the javascript object constructor function.
If you use multiple similar widgets, there can be a savings in typing errors if you declare objects that hold their initialization settings and load them programmatically instead of declaring all the shared properties in the markup for each one declaratively. Another reason I prefer programmatic instantiation is that I can change the instantiation parameters based on different conditions before actually starting up a widget more easily than if I had to do it server-side to change the markup.
Since version 1.6, Dojo supports HTML5 data attributes, so the resulting HTML will be valid. Despite the performance penalty, the declarative approach allows to see the structure of the UI at a glance.
I copied the comparison between styles they provide in the announcement of the HTML5 data attribute-support:
Even when leveraging the new HTML5-valid custom attributes, there are still pros and cons to declaring widgets within HTML instead of with JavaScript. Declaring JavaScript components from within HTML introduces semantic impurity since the HTML is no longer is purely semantic markup, but includes tight coupling to particular visual components. The declarative approach also incurs extra CPU cycles because the dojo.parse() must traverse the DOM tree to find elements with Dojo custom attributes. Programmatic instantiation avoids unnecessary cycles and preserves semantic purity of HTML. However, markup-based widget declaration still has a powerful advantage by allowing us to define and create a widget in a single place, facilitating rapid application development with minimal effort.

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

JSONML vs. InnerHTML vs.?

First of all, am I the only person using JSONML? And second of all, would you recommend using JSONML for inserting dynamic HTML or is InnerHTML more efficient?
Bare in mind that (in IE) not every innerHTML is writable (innerHTML isn't standar compilant anyway). So closer you come to appending nodes rather then inserting html, better you are. As far as I can see, jsonml thingie creates DOM elements whch is nice. I can only sugest you to make some huge dataset, insert it in two different ways and mesure performance yourself.
While superficially used to perform similar tasks, JsonML and innerHTML are quite different beasts.
innerHTML requires you to have all the markup exactly as you want it ready to go, meaning that either the server is rendering the markup, or you are performing expensive string concatenations in JavaScript.
JsonML opens the door to client-side templating through JBST which means that your template is converted from HTML markup into a JavaScript template at build time. At runtime, you simply supply the data and you end up with DOM elements to be inserted or to replace an existing element (something innerHTML cannot easily do without extra DOM creation). Rebinding only requires requesting additional data, not the entire re-rendered markup. This is where large performance gains can be made as the markup can be requested/cached separately from the data.
For simplicity, innerHTML has been the preferred method for the HTML-Message pattern style of Ajax. But tool-sets like JsonFx can make using JsonML and JBST just as easy while delivering a full browser-side templating Ajax pattern.
JsonML and the connected libraries (templating, etc.) seem to offer an efficient way of generating dynamic HTML on the client side.
When I say efficient I mean, I mean that the programmer does not waste time or effort while completing his task. But I am not sure if you meant to ask whether using innerHTML is faster and requires less resources on the client side.

Alternative "architectural" approaches to javaScript client code?

How is your javaScript code organized? Does it follow patterns like MVC, or something else?
I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":
The 'model' is a JSON tree that gets extended with helpers
The view is the DOM plus classes that tweak it
The controller is the object where I connect events handling and kick off view or model manipulation
I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"
Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
..but Javascript has many facets that are OO.
Consider this:
var Vehicle = jQuery.Class.create({
init: function(name) { this.name = name; }
});
var Car = Vehicle.extend({
fillGas: function(){
this.gas = 100;
}
});
I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).
This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.
JavaScriptMVC is a great choice for organizing and developing a large scale JS application.
The architecture design very well thought out. There are 4 things you will ever do with JavaScript:
Respond to an event
Request Data / Manipulate Services (Ajax)
Add domain specific information to the ajax response.
Update the DOM
JMVC splits these into the Model, View, Controller pattern.
First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.
$.Controller.extend('TodosController',{
'click' : function(el, ev){ ... },
'.delete mouseover': function(el, ev){ ...}
'.drag draginit' : function(el, ev, drag){ ...}
})
Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:
Todo.findAll({after: new Date()}, myCallbackFunction);
Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view.
'.show click' : function(el, ev){
Todo.findAll({after: new Date()}, this.callback('list'));
},
list : function(todos){
$('#todos').html( this.view(todos));
}
In 'views/todos/list.ejs'
<% for(var i =0; i < this.length; i++){ %>
<label><%= this[i].description %></label>
<%}%>
JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:
Code generators
Integrated Browser, Selenium, and Rhino Testing
Documentation
Script compression
Error reporting
MochiKit is great -- and was my first love, so-to-speak, as far as js libraries go. But I found that while MochiKit has very expressive syntax, it didn't feel nearly as comfortable to me as Prototype/Scriptaculous or jQuery did for me.
I think if you know or like python, then MochiKit is a good tool for you.
Thank you all kindly for your answers. After some time, I'd like to post what I've learned so far.
So far, I see a very large difference the approach using something like Ext, and others like JQuery UI, Scriptaculous, MochiKit, etc.
With Ext, the HTML is just a single placeholder - UI goes here. From then on, everything is described in JavaScript. DOM interaction is minimized under another (perhaps stronger) API layer.
With the other kits, I find myself starting by doing a bit of HTML design, and then extending the DOM directly with snazzy effects, or just replacing the form input here, an addition there.
The major differences start to happen as I need to deal with event handling, etc. As modules need to "talk" to each other, I find myself needing to step away from the DOM, abstracting it away in pieces.
I note that many of these libraries also include some interesting modularization techniques as well. A very clear description is contributed on the Ext website, which includes a fancy way to "protect" your code with modules.
A new player I haven completely evaluated is Sproutcore. It seems like Ext in approach, where the DOM is hidden, and you mostly want to deal with the project's API.
Tristan, you will find that when you try to architecture JavaScript as an MVC application it tends to come up short in one area -- the model. The most difficult area to deal with is the model because the data does not persist throughout the application, and by nature the models seem to change on the client-side pretty consistently. You could standardize how you pass and receive data from the server, but then at that point the model does not really belong to JavaScript -- it belongs to your server-side application.
I did see one attempt awhile back where someone created a framework for modeling data in JavaScript, much like the way SQLite belongs to the application. It was like Model.select( "Product" ) and Model.update( "Product", "Some data..." ). It was basically an object notation that held a bunch of data to manage the state of the current page. However, the minute you refresh, all that data is lost. I'm probably off on the syntax, but you get the point.
If you are using jQuery, then Ben's approach is really the best. Extend the jQuery object with your functions and properties, and then compartmentalize your "controllers". I usually do this by putting them into separate source files, and loading them on a section-by-section basis. For instance, if it were an e-commerce site, I might have a JS file full of controllers that handle functionality for the checkout process. This tends to keep things lightweight and easy to manage.
Just a quick clarification.
It is perfectly feasible to write GWT apps that are not server-oriented. I am assuming that from Server-Oriented you mean GWT RPC that needs java based back-end.
I have written GWT apps that are very "MVC-ish" on the client side alone.
The model was an object graph. Although you code in Java, at runtime the objects are in javascript with no need of any JVM in either client or server-side. GWT also supports JSON with complete parsing and manipulation support. You can connect to JSON webservices easily, see 2 for a JSON mashup example.
View was composed of standard GWT widgets (plus some of our own composite widgets)
Controller layer was neatly separated from View via Observer pattern.
If your "strongly-typed" background is with Java or similar language, I think you should seriously consider GWT for large projects. For small projects I usually prefer jQuery. Upcoming GWTQuery that works with GWT 1.5 may change that though not in near future because of abundance of plugins for jQuery.
Not 100% sure what you mean here, but I will say that after doing ASP.NET for the last 6 years, my web pages are now mostly driven by JavaScript once the basic page rendering is done by the server. I use JSON for everything (have been for about 3 years now) and use MochiKit for my client-side needs.
By the way, JavaScript is OO, but since it uses prototypical inheritance, people don't give it credit in that way. I would also argue that it is functional as well, it all depends on how you write it. If you are really interested in functional programming styles, check out MochiKit - you may like it; it leans quite a bit towards the functional programming side of JavaScript.

Categories

Resources