To integrate UI control and the data it is representing is always a challenge. Asp.Net has data binding feature which perfectly works. But with Ajax type application, data rendering should be conducted from client side. MS lately has a jQurey plugin, it is a cute solution for client data binding.
Instead of:
var clRec = "";
for(var i=0; i<client.name.length; i++) {
clRec += "<li><a href='clients/"+client.id[i]+"'>" + client.name[i] + "</a></li>";
}
It is a lot better:
<li><a href="clients/${id}">${name}</a></li>
The better way is actually showing a templete. There are two things that have to be done first to make a template work: define a data instance that is to be bound to the template; and determine the data instance is a singlar data or a collection, so as to determine a loop of the template is needed to render the template.
MS jQuery Template plugin solution
To have reference:
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>
To define data instance:
var clientData = [
{ name: "Rey Bango", id: 1 },
{ name: "Mark Goldberg", id: 2 },
{ name: "Jen Statford", id: 3 }
];
To define template
<script id="clientTemplate" type="text/html">
<li><a href="clients/${id}">${name}</a></li>
</script>
To specify data binding:
$("#clientTemplate").tmpl(clientData).appendTo( "ul" );
appendTo is to hook the html tag where the rendered template result will apply.
An example (courtesy of [1])
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var clientData = [
{ name: "Rey Bango", id: 1 },
{ name: "Mark Goldberg", id: 2 },
{ name: "Jen Statford", id: 3 }
];
$("#clientTemplate").tmpl(clientData).appendTo( "ul" );
});
</script>
<script id="clientTemplate" type="text/html">
<li><a href="clients/${id}">${name}</a></li>
</script>
</head>
<body>
<ul></ul>
</body>
</html>
1. http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts
Tuesday, September 21, 2010
Sunday, December 6, 2009
Javascript Interpreter Optimization
Good code requires less effort for interpreter to execute. Look the following code snippet:
for(var i=0; i<count; i++){
$get('divContent').appendChild(element[i];
}
Every time of the loop requires interpreter to execute $get method to find the divContent element, that should be avoid because each time the element is the same.
var divContent = $get('divContent');
for(var i=0; i<count; i++){
divContent.appendChild(elementp[i]);
}
Above code is better because it only need the interpreter find divContent element once. It can be even better:
var divContentAppendChild = $get('divContent').appendChild;
for(var i=0;i<count;i++){
divContentAppendChild(element[i]);
}
Above code using delegate saves time for the interpreter to lookup the scope chain for the function.
Of cause we can apply the following way to append a group of elements to an exist element by assigning it's innerHtml attribute.
$get('divContent').innerHtml = strContent;
Define javascript array in two ways:
var links = ["microsoft.com", "yahoo.com", "cbc.ca"];
var strArray = new Array();
strArray.push("<div>");
strArray.push("some content");
strArray.push("/div");
for(var i=0; i<count; i++){
$get('divContent').appendChild(element[i];
}
Every time of the loop requires interpreter to execute $get method to find the divContent element, that should be avoid because each time the element is the same.
var divContent = $get('divContent');
for(var i=0; i<count; i++){
divContent.appendChild(elementp[i]);
}
Above code is better because it only need the interpreter find divContent element once. It can be even better:
var divContentAppendChild = $get('divContent').appendChild;
for(var i=0;i<count;i++){
divContentAppendChild(element[i]);
}
Above code using delegate saves time for the interpreter to lookup the scope chain for the function.
Of cause we can apply the following way to append a group of elements to an exist element by assigning it's innerHtml attribute.
$get('divContent').innerHtml = strContent;
Define javascript array in two ways:
var links = ["microsoft.com", "yahoo.com", "cbc.ca"];
var strArray = new Array();
strArray.push("<div>");
strArray.push("some content");
strArray.push("/div");
Variable Scope with Javascript
Keyword "var" enforces declare a local variable. Otherwise it will be global. Inapproperate use of global variable voilate the idea of OOP, because it has no enforcement of encapsulation. In addition, global variables make code hard to read, maintain, and error prone.
Look at the following code:
function f1()
{
i=10;
fz();
alert(i); // i=100
}
function fz()
{
for(i=0; i++; i<=100)
{
}
}
In function fz, i is considered as global by the compiler/interpreter. To avoid this unexpected result, user "var".
in f1
var i = 10; // tell the compiler this i is a local i (local to the including {})
in f2
for(var i=0 ...)
Another note, even Javascript is a weak-typed language, variable has types too as in other languages. "typeof" operator gets the type of a variable.
typeof x == "string"|"function" |"undefined" ...
Look at the following code:
function f1()
{
i=10;
fz();
alert(i); // i=100
}
function fz()
{
for(i=0; i++; i<=100)
{
}
}
In function fz, i is considered as global by the compiler/interpreter. To avoid this unexpected result, user "var".
in f1
var i = 10; // tell the compiler this i is a local i (local to the including {})
in f2
for(var i=0 ...)
Another note, even Javascript is a weak-typed language, variable has types too as in other languages. "typeof" operator gets the type of a variable.
typeof x == "string"|"function" |"undefined" ...
Friday, January 9, 2009
Smart Page Scroll after Postback
For a long extended page, it is devastating that you need to scroll the mouse to the location where you are working after each time of a postback. Here, I am going to discuss a solution with javascript features.
Window.ScrollTo(xpos, ypos) is a useful function, we can easily scroll a page to a exact location. However it brings another issue - we need to determine the pixel coordinates, which is usually not gotten for free.
Using scrollIntoView(alignment) method is more practical by scrolling to a specified control. Every html control has this method. The parameter "alignment" indicates top-top or bottom-bottom alignment condition that affect the exact location scrolled to.
List 1 shows a method to be used in an asp.net page or user control class.
[list 1]
/// <summary>
/// Scroll the page to a location where given control is visible
/// </summary>
/// <param name="ctrlClientId">control's client id</param>
private void ScrollToControl(string ctrlClientId)
{
string jsScript = "<SCRIPT language=\"javascript\"> document.getElementById('" + ctrlClientId + "').focus(); document.getElementById('"
+ ctrlClientId + "').scrollIntoView(true) </SCRIPT>";
Page.RegisterStartupScript("controlFocus", jsScript);
}
To call the method, we only need to pass in a web control's client id (list 2).
[list 2]
this.ScrollToControl(this.trColumns.ClientID);
Instead of being placed in a page or user control, this method can be placed in a common place so as to make it shared across whole application. Among tons of options, it can find a niche in Global class (list 3).
// in Global.asax.cs:
public class Global : System.Web.HttpApplication
{
// insert static SetFocus method here, just below the class Global declaration:
public static void SetFocus(System.Web.UI.Page webPage)
{
string[] pbCtrl = webPage.Page.Request.Form.GetValues("__EVENTTARGET");
if (pbCtrl != null && pbCtrl.Length > 0)
{
string ctrlId;
ctrlId = pbCtrl[0];
System.Web.UI.Control ctrlFound = webPage.Page.FindControl(ctrlId);
if ((ctrlFound != null) &&
(
ctrlFound is System.Web.UI.WebControls.DropDownList ||
ctrlFound is System.Web.UI.WebControls.TextBox ||
ctrlFound is System.Web.UI.WebControls.RadioButton ||
ctrlFound is System.Web.UI.WebControls.RadioButtonList))
{
string ctrlClientId;
ctrlClientId = ctrlFound.ClientID;
string strScript;
strScript = "<SCRIPT language=\"javascript\"> document.getElementById('" + ctrlClientId + "').focus(); document.getElementById('"
+ ctrlClientId + "').scrollIntoView(true) </SCRIPT>";
webPage.Page.RegisterStartupScript("controlFocus",strScript );
}
}
}
// In your Page_Load handler for (any page:
private void Page_Load(object sender, System.EventArgs e)
{
// insert this conditional call to the SetFocus Method:
if(IsPostBack) Global.SetFocus(this);
}
Window.ScrollTo(xpos, ypos) is a useful function, we can easily scroll a page to a exact location. However it brings another issue - we need to determine the pixel coordinates, which is usually not gotten for free.
Using scrollIntoView(alignment) method is more practical by scrolling to a specified control. Every html control has this method. The parameter "alignment" indicates top-top or bottom-bottom alignment condition that affect the exact location scrolled to.
List 1 shows a method to be used in an asp.net page or user control class.
[list 1]
/// <summary>
/// Scroll the page to a location where given control is visible
/// </summary>
/// <param name="ctrlClientId">control's client id</param>
private void ScrollToControl(string ctrlClientId)
{
string jsScript = "<SCRIPT language=\"javascript\"> document.getElementById('" + ctrlClientId + "').focus(); document.getElementById('"
+ ctrlClientId + "').scrollIntoView(true) </SCRIPT>";
Page.RegisterStartupScript("controlFocus", jsScript);
}
To call the method, we only need to pass in a web control's client id (list 2).
[list 2]
this.ScrollToControl(this.trColumns.ClientID);
Instead of being placed in a page or user control, this method can be placed in a common place so as to make it shared across whole application. Among tons of options, it can find a niche in Global class (list 3).
// in Global.asax.cs:
public class Global : System.Web.HttpApplication
{
// insert static SetFocus method here, just below the class Global declaration:
public static void SetFocus(System.Web.UI.Page webPage)
{
string[] pbCtrl = webPage.Page.Request.Form.GetValues("__EVENTTARGET");
if (pbCtrl != null && pbCtrl.Length > 0)
{
string ctrlId;
ctrlId = pbCtrl[0];
System.Web.UI.Control ctrlFound = webPage.Page.FindControl(ctrlId);
if ((ctrlFound != null) &&
(
ctrlFound is System.Web.UI.WebControls.DropDownList ||
ctrlFound is System.Web.UI.WebControls.TextBox ||
ctrlFound is System.Web.UI.WebControls.RadioButton ||
ctrlFound is System.Web.UI.WebControls.RadioButtonList))
{
string ctrlClientId;
ctrlClientId = ctrlFound.ClientID;
string strScript;
strScript = "<SCRIPT language=\"javascript\"> document.getElementById('" + ctrlClientId + "').focus(); document.getElementById('"
+ ctrlClientId + "').scrollIntoView(true) </SCRIPT>";
webPage.Page.RegisterStartupScript("controlFocus",strScript );
}
}
}
// In your Page_Load handler for (any page:
private void Page_Load(object sender, System.EventArgs e)
{
// insert this conditional call to the SetFocus Method:
if(IsPostBack) Global.SetFocus(this);
}
Wednesday, October 1, 2008
Difference between javascript 1.2 and 1.3
Javascript 1.3 added two new objects:
Object object
Function object
Different Behavior with Condition
In following code, javascript 1.3 and 1.2 produce different result.
var a = new Boolean(false);
if(a){
alert('the message is' + a);
}
javascript 1.3 treates a as true instead of false which 1.2 does. javascript check if the expression result is null or undefined, if not it treat it as true.
<script language='javascript'&lgt;
By default, it uses javascript 1.3 with common used browsers. To use 1.2, you will need to explicitely specify javasctipt 1.2
<script language='javascript 1.2'&lgt;
Object object
Function object
Different Behavior with Condition
In following code, javascript 1.3 and 1.2 produce different result.
var a = new Boolean(false);
if(a){
alert('the message is' + a);
}
javascript 1.3 treates a as true instead of false which 1.2 does. javascript check if the expression result is null or undefined, if not it treat it as true.
<script language='javascript'&lgt;
By default, it uses javascript 1.3 with common used browsers. To use 1.2, you will need to explicitely specify javasctipt 1.2
<script language='javascript 1.2'&lgt;
Tuesday, September 30, 2008
Javascript consumes Xml File
<race>
<yatch raceNo='74'>
<name>wanderer</name>
<skipper>Walter Jeffries</skipper>
<helm>Sally Jacobs</helm>
</yatch>
</race>
Javascript load a xml file
into memory and create an object for accessing
var myXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
myXmlDoc.async = false;
myXmlDoc.load("exampleDoc.xml");
// access elements
myXmlDoc.childNotes(0).childNodes(1).tagName;
myXmlDoc.childNotes(0).getAttribute("raceNo");
myXmlDoc.childNotes(0).childNotes(1).text;
<yatch raceNo='74'>
<name>wanderer</name>
<skipper>Walter Jeffries</skipper>
<helm>Sally Jacobs</helm>
</yatch>
</race>
Javascript load a xml file
into memory and create an object for accessing
var myXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
myXmlDoc.async = false;
myXmlDoc.load("exampleDoc.xml");
// access elements
myXmlDoc.childNotes(0).childNodes(1).tagName;
myXmlDoc.childNotes(0).getAttribute("raceNo");
myXmlDoc.childNotes(0).childNotes(1).text;
Saturday, September 6, 2008
Javascript Image Rollover
var homeOff = new Image();
homeOff.src = "homeoff.gif";
var homeOn = new Image();
homeOn.src = "homeon.gif";
function act(imgName, action){
if(document.images){
document.images[imgName].src = eval(imgName+action+".src");
}
}
<img src="homeoff.gif" name="home">
<a href="..." onMouseOver="act("home","On");" onMouseOut="act('home', 'Off');">
homeOff.src = "homeoff.gif";
var homeOn = new Image();
homeOn.src = "homeon.gif";
function act(imgName, action){
if(document.images){
document.images[imgName].src = eval(imgName+action+".src");
}
}
<img src="homeoff.gif" name="home">
<a href="..." onMouseOver="act("home","On");" onMouseOut="act('home', 'Off');">
Javascript Anonymous Function
The Format
var func = new Function("p1", "p2",...,"pn", "function body");
A Example
var sayHello = new Function("toWhom", "alert('Hi, '+toWhom);");
sayHello("World.");
Note:
"Function" is class and it starts with a capital letter. Camel
var func = new Function("p1", "p2",...,"pn", "function body");
A Example
var sayHello = new Function("toWhom", "alert('Hi, '+toWhom);");
sayHello("World.");
Note:
"Function" is class and it starts with a capital letter. Camel
Subscribe to:
Posts (Atom)