jQuery: Templating data - javascript

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

Related

How to create knockout data bindings at runtime w/o data attributes

Is it possible to create knockout bindings from javascript alone, i.e. without writing custom html attributes?
I'm very much stuck with our existing markup and can't add data-bind etc. that knockout.js relies on (html is generated programmatically and there is no access to the rendering pipeline, please assume I've exhausted my options in trying :)
One idea that I'm tentatively pursuing is adding data-bind attributes at runtime prior to calling ko.applyBindings. Is there a preferred approach? I'll also accept an alternative, sufficiently documented/popular/stable framework if it also implements bindings similar to knockout.js if/visible.
Knockout 3.0 (which just around the corner and is in release candidate now) opens up a lot more ways to interact with the binding process, such as the ability to preprocess nodes and dynamically generate bindings. Take a look at Knockout.Punches to see some examples of what is possible. Between that and the things already mentioned like the unobtrusive and class binding providers, you should have no trouble working with whatever markup you're stuck with.
It may also be worth pointing out knockout has an applyBindingsToNode function which takes in a JSON object of the bindings if you want full control, though that does not apply bindings to descendant elements.
Knockout allow us to create custom binding provider, I find out there is several libs that help you to do it
You can find them here:
One that don't use DOM at all:
https://github.com/tobio/knockout.unobtrusivebindingprovider
One that use another approach :
https://github.com/rniemeyer/knockout-classBindingProvider
At last resort if none of them suit your needs, you can with jQuery modify the DOM then call the binding on it...
Look at the "Unobtrusive event handling" section in the Knockout documentation under "Further techniques".

Build backbone models from existing html

I'm not particularly good at javascript frameworks, I decided to use Backbone to help organize my code since my project got bigger.
The problem is, I didn't had javascript templates (or Views) in mind when I designed the first 10k lines on my project. I'm already using a templating engine (PHP smarty).
The premises: I already have a good HTML template. As an example I have an <article> element which contains the content of a blog post. It's ok, because I can build a Model out of this element. But what about the View? I don't have a template nor do I want to actually use one (because I have to reorganize everything).
The question is: how do I bind all the possible variables in an <article> (which could be for example the value of <timestamp> element, outerHTML of the content div, etc) to an object view?
All the examples, tutorial I've seen, uses a template which is used to generate the HTML. I'm not really comfortable in defining a underscore.js template.
The CRUD operations on articles, comments, etc would be done with $.ajax(). I don't want to do additional http requests just to get all the posts of a page (since the backend already does this).
You can use the setElement method to do what you want (or at least attach your view to an existing element in the dom, then your view will need to know what to do with it)
http://backbonejs.org/#View-setElement

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

Is assigning html to javascript variable a good practice?

I am a newbie to html/css/javascript and code like this really scares me:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows
Is assigning html to javascript variable a good practice? or I hope there is a substitute.
There is nothing wrong with it. After all, it is really no different then typing the same thing outside of the javascript block.
I do however find, that the formatting and the likes can be annoying. On use JQuery a fair bit, and depending on what I might be doing I might use a .html() or .clone() method to create html form another element.
JQuery also has a template plugin which when used does allow for you to get slightly better formatting, and you can also specify dynamic values. Which is great for creating dynamic tables that update with Ajax for example.
Another side note, the fact that example you gave was on a Google site, would usually be enough to convince me it is OK to do ;)
There's nothing bad in it. People have been doing this since there was a thing called DHTML :-)
AFAIK, this is one of the most performant ways to build a part of document (later to be inserted to DOM or whatever).
In this case you have to, since google Maps API requires explicitly to pass a HTML content (and not a reference to some hidden element in page or loaded via ajax).
This don't mean it's a bad practice: for example, I always use a HTML string along with some custom template system, so that I can pass infowindow HTML in a loop, changing dynamically some chunks of markup with data retrieved by a JSON.
Anyway you can still use an element into the DOM and then pass its outerHTML string to the API if this makes your application more performant with an improved maintainability

jQuery - some beginner questions

I'm a very beginner to jQuery, and I'm having some basic questions:
Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?
Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?
When it comes to executing a script when the page is done loading, what way is preferred?
$(document).ready(function() {})
$(function() {})
$().ready(function() {})
They seem to all do the same thing, but what is the preferred way of scripting?
Yes. This way your JS is cleanly separated from your html. You can look at your file and in one glance, see how it is affecting your HTML. If it was embedded in the HTML, you would have to look for onClick, onLoad etc and it can get pretty messy for large applications.
Client browsers will cache files, so if you use the google version of JQuery, it will not have to download it off your server. Saving you bandwidth.
$(document).ready(function() {}) Is the preferred choice. $(function() {}) Just defines the block for execution, it will only execute after the page is ready if it is the last thing on the page to get executed.
1.) Yes and No. It is considered best practice to bind events unobtrusive regardless of using jQuery or not (this means, strictly separate javascript, html and any other language). Since jQuery allows to easily bind events it's a better way to use inline-handlers.
2.) You should use a CDN (like google) to deliver static files like jQuery for Caching purposes + they have a huge server network which may even be faster than your own host.
3.) I would stick to the first two calls. Anyway, basically they all will do it, but the best readability probably has $(document).ready(function() {});
1) Keep all your event binding in your script. This makes it easy to change later. You'll also appreciate having a single place to look for all event-related logic.
2) This has been answered very well already.
3) I prefer #2 for its brevity, but really the ideal way to do it is like this:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
That avoid conflicts if you are using other frameworks that define $.
1: no this is completely up to you. generally jQuery incurs a performance penalty, because it is an extra layer of abstraction. Only use it, if you feel it helps you do your job easier. However, unless you truely need to optimize for performance the benefit in using it will far outway the cost. jQuery gives you tried and tested crossbrowser compatibility, which, if you wish to cater to all the different browsers out there, can be a costly affair to implement yourself.
2: Use Googles version: that way there is a chance that your users already have it cached and don't need to load it again from your site.
3: 2nd option, the shortcut is very widely used to a point where i'd say it's prefered even though 1st option is nice and specific. I'd never use 3rd option
For the 3d point, none of them. it is generally recommended, for performance reasons, to place your scripts just before the closing </body> tag. Thus you will not need to wait for the ready event: at this stage, the page is already loaded.
Check Jquery Cookbox (O'Reilly), Chapter 1.2: Executing jQuery/JavaScript Coded Ater DOM Has Loaded but Before Complete Page Load (that book is a must read all in all)
To have a quick idea about this technique, check Move jQuery to the end of body tag? (there are many other posts on SO about this subject)
I personally don't subscribe to the "cleanly separate JS from HTML" philosophy. I rarely see real world use cases where that has any benefit. Separating HTML from JS often leads to buttons that say "click here to do X" in the HTML but do nothing unless the appropriate javascript is with them. Kind of misses the point.
With the case of jQuery and events... I find it much easier to debug an app if I can inspect an HTML button in firebug and see what that button does (by looking at the onclick attribute).
Using the google version can aid with caching, but don't link directly to jquery.com. We did that here once and they went down, took us with them.

Categories

Resources