DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Eloquent JavaScript - JavaScript Tutorials

Marijn Haverbeke has put together an e-book named Eloquent JavaScript that not only has great content, but also comes with an integrated interface for editing and running the examples directly from the "pages."

I had to post this since the site is such an excellent resource for JavaScript. Running the examples is incredibly intuitive and easy. Excellent work on Mr. Haverbeke's part!

The post/link originated on Ajaxian: http://ajaxian.com/archives/eloquent-javascript 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Tuesday, January 22, 2008 4:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

TypeWatch: jQuery Plugin

Earlier this week I created a jQuery plug-in that allows you to potentially determine when a user has finished typing in a textbox. I created it for a search textbox on one of my websites so that I could return results by firing some AJAX after they're done typing. It could help with an AJAX auto-complete implementation too.

[UPDATED 05/16/08]

There are 4 settings you can set:

1. callback: The function to callback after the user has "finished" typing. Default void.
2. wait: The number of milliseconds to wait before the plugin considers that typing has finished. Default 750.
3. highlight: Aesthetics, determines if the text should be highlighted when the textbox receives focus. Default true.
4. captureLength: The minimum amount of characters necessary before allowing the event to fire. Default 2.

How it works:

For each textbox or textarea matched through jQuery it creates a timer which gets reset upon every [KeyDown] event. If the timer's [wait] is reached then the user has finished typing, or stopped typing long enough for the timer to reach its [wait] interval.

The callback will not execute if the length of text is less than captureLength. Also, if the timer's [wait] interval is reached and the text has not changed it will not execute the callback. So if you change "some text" to "SOME TEXT" the callback will not execute. The callback will be executed when the ENTER key is pressed on single-line INPUT elements.

You can get the debug and packed version at: http://jquery.com/plugins/project/TypeWatch

The latest version 2.0.0 is a complete refactor of code and includes a few issue fixes. Code has been refactored thanks to Charles Christolini - BinaryPie.com

DEMO:

Click here for the Live Demo

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Friday, August 17, 2007 5:23 AM
Permalink | Comments (115) | Post RSSRSS comment feed

JavaScript Model Objects (JMO) - An Idea

A rough prototype of what I like to call "JavaScript Model Objects" or JMO for short.While playing with ASP.NET AJAX I came across an idea of using AJAX, JSON, and JavaScript to bind data onto page elements. So today I decided to play around and try to create a "repeater" but on the client-side. This is the gist of the idea...

#1. Get the data which I want to bind using AJAX and JSON.

Example JSON data: 

var myTestObj =
{
            "rows":
                        [{"id":1, "title":"Test one", "imagesrc":"images/ajax.gif", "isTest":true},
                        {"id":2, "title":"Test two", "imagesrc":"images/playmini.gif", "isTest":true},
                        {"id":3, "title":"Test three", "imagesrc":"images/playmini.gif", "isTest":true}]
}

In this example the JSON data must have "rows" with an array of the row columns/values.

#2. Define the template that I want to bind to. This is defined directly on my HTML page.

Example:

<table>
            <tr id="JMO1">
                        <td style="border: solid 1px black">!id!</td>
                        <td style="border: solid 1px black">!title!</td>
                        <td style="border: solid 1px black"><img src="!imagesrc!" /></td>
                        <td style="border: solid 1px black">!isTest!</td>
            </tr>
</table>

As you can see I have a table with 4 columns. I want to bind to the TR object so I give my TR an id. The places where I want the data to appear are surrounded by exclamation points, like !<name>!. Also notice that I have given the TR tag an ID of "JMO1" which I will use to pass to my binding function. The TR tag is essentially my "Model Object."

#3. The functions to bind the data to my model object... Please note this is a very rough sketch of the functionality, and yes I am using jQuery:

function initJMO(modelObj, dataObj) {    
        var obj = $(modelObj);
        var data = eval(dataObj);
        var dataMembers = getDataMembers(obj)
                  
        if (dataMembers.length > 0) {
                    // Deep clone the model, save reference
                    //var clone = obj.clone(true);
                    var dataClone = obj[0].outerHTML;
                    
                    for (x = data.rows.length-1; x >= 0; x--) {
                          var thisRow = dataClone;
                                   
                          for (i = 0; i < dataMembers.length; i++) {
                                  var rg = new RegExp("!" + dataMembers[i] + "!"); rg.global = true;

                                  if (dataMembers[i] == "length") {
                                         ev = data.rows.length.toString();
                                  } else {
                                         ev = eval("data.rows[" + x + "]." + dataMembers[i]).toString();
                                  }
                                        
                                  thisRow = thisRow.replace(rg, ev);
                          }

                          obj.after(thisRow);
                    }
                            
                    // Remove model
                    obj.remove();
        }
}

function getDataMembers(obj) {
              var str = obj[0].outerHTML;

              if (str.length > 0) {
                          var rg = /!(\w+)!/g;
                          var match = str.match(rg);
                          var dMembers = [];
                          dMembers.push("length");

                          if (match != null) {
                                      for(i = 0; i < match.length; i++) {
                                            dMembers.push(match[i].replace(/!/g,""));
                                      }
                          }

                          return dMembers;
              } else {
                          return [];
              }
}

$(function() {
              initJMO("#JMO1", myTestObj);
} );

initJMO requires 2 params... 1 is the model object (our TR in this case). 2 is the data object (our un-eval'd JSON). 

initJMO clones the model object, finds all the data members (column names) we want to bind to and then goes through and replaces each !<name>! with the corresponding JSON column's data. It then appends the source of our cloned/replaced element after the model object, thus repeating the data with each row of our data object. Finally initJMO removes the model object from the page.

So what you get is your model object repeated with every row of your data object.

The cool thing about this is you can define ANY element as the model object!Now yes this still needs a lot of work and there are a few issues with it but I'd like to get some feedback. Good idea? Has this been done before?

A sample page can be viewed here: http://www.dennydotnet.com/Test/Default2.aspx

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Friday, August 10, 2007 4:48 PM
Permalink | Comments (19) | Post RSSRSS comment feed

ASP.NET AJAX createDelegate and the JavaScript "this"

If you're doing ASP.NET AJAX and you're creating a lot of JavaScript then you are hopefully aware of the Function.createDelegate method. If you're not using the createDelegate method then read on!

When you're building your classes in ASP.NET AJAX you'll have various function that interact with each other. Sometimes you may even have external methods that you're calling. So when you want to reference a javascript object you would probably pass the object through the parameters list. When it comes to doing a Web Service call you have a callback method for success and fail such as:


var el = this;
Client.GetSomeField(1, 5, onSuccess, onFail);

function onSuccess(r) {
 var el = this;
 alert(r);
}


Everything looks dandy. However when I use "this" inside any of the callback methods I won't get the object I am looking for. Lets say I wanted to pass "this" object to my onSuccess function. How could I do that? Well that's where the createDelegate comes in:


var el = this;
var newSuccess = Function.createDelegate(el, onSuccess);

Client.GetSomeField(1, 5, newSuccess, onFail);

function onSuccess(r) {
 // You now have access to the same object using "this"
 var hw = this.HelloWorld();
 alert(r + hw);
}


Wow well that was easy! The cool thing about this is that you can pass any object with the createDelegate method. So if I wanted to pass a string I could do:


var el = "Hey I came from down the way";
var newSuccess = Function.createDelegate(el, onSuccess);

Client.GetSomeField(1, 5, newSuccess, onFail);

function onSuccess(r) {
 var hw = this; // this = "Hey I came from down the way"
 alert(r + hw);
}


Tada! I just passed my string across.

Well now wait a second, I have another function that takes in a few extra params. It's not within a Web Service method, it's an external function. How do I use createDelegate with that?


var el = this;
var newSuccess = Function.createDelegate(el, onSuccess);

// Call the function
newSuccess(param1, param2, param3);

function onSuccess(p1, p2, p3) {
 // still the same object that we passed
 var hw = this.HelloWorld();
 hw += p1;
 hw += p2;
 hw += p3;
 alert(hw);
}


The createDelegate method takes two parameters. The first one is the object that will be referenced by "this" (inside the function). The second parameter is the function to be executed (where you'll use "this").

Another good trick is to use the createDelegate function with the $addHandler method:


$addHandler(btnSave, 'click', Function.createDelegate(someOtherObj, this.onSaveClicked));


So in conclusion, why use createDelegate? It wraps an existing function and returns a new function which can use the "this" keyword that points to an object of your desire. Why do I need this? In an event handler raised by a DOM element the "this" keyword will refer to the DOM element whereas you may want it to refer to a class or class object, or any other object for that matter.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Tuesday, July 24, 2007 8:57 AM
Permalink | Comments (0) | Post RSSRSS comment feed

New Dad, Job and Knowledge

Well it's been a long while since I've blogged and I'm finally getting around to it. There's been a lot of things going on lately! First and foremost I'm going to be a new Dad starting next year around February or March. I'm excited about the news and can't wait to find out if it's a boy or girl. Things will definitely start changing around the house!

Secondly, I started a new job! I'm really excited about working at this new place because they're doing some really cool AJAX stuff. It's a great opportunity for me because I'll get to work with some really bright people and work with the latest technologies too. I recently picked up a book titled: "Professional ASP.NET 2.0 AJAX" by Matt Gibbs and Dan Wahlin (Amazon) to get some further insight on the ASP.NET AJAX Framework. It's an excellent book and there's plenty of tips and knowledge in here even if you're experienced. For example, I finally found out what the benefit of using the ASP.NET AJAX registration methods (for namespaces, classes, etc...). It has to do with performance, amongst other things. I'll blog more about this later! On another note I introduced SubSonic to the team as well. I had some positive feedback and it looks like we could be implementing it across various projects in the future.

I've recently been working with the ASP.NET AJAX Serialization classes, in particular the JSON serializer. There didn't seem to be too many resources while Googling for examples so I poked around and created a few helper functions for myself such as serializing a DataTable or DataReader into a JSON array / object (Yes ASP.NET Futures supports this already). I'll blog about this in the future as well. Anyways, upon creating some helper functions I realized I had something interesting started. I began thinking about how I could bind my array of JSON objects to a pre-defined template, like a Repeater only on the client-side. It seems possible but I haven't researched this thoroughly to see what implications it could have. It may be a side project in the future.

Feedback:
What I'm interested in knowing is how other people have been using ASP.NET AJAX. Are you taking adavntage of Web Services, or are you using PageMethods? Are you relaying your data as XML or JSON? Why? How are you using the data passed to the client. For example are you using it to update one or two specific elements or are you bulking your objects together to complete multiple tasks?

I'm very interested in hearing your responses.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Monday, July 16, 2007 5:05 PM
Permalink | Comments (2) | Post RSSRSS comment feed

Tips: Debugging JavaScript

I've finally been making headway on my project. It's been slow and I haven't been able to devote much time to it recently but it is coming along and it looks sweet!

Anyways, I read a recent post on Mads Kristensen's blog about debugging JavaScript in Visual Studio 2005. I've been debugging JS in the method described on his blog for quite some time now and thought I would share some tips I picked up on.

Tip #1: Debugging inside an iterator
The problem is I was using Prototype 1.5.0's extensibility to work with my arrays. There are quite a few iterators that were introduced in Prototype including (to name a few) .each and .find. These two iterators allow you to iterate through each item in your array. Here is a quick example of how these functions are used:

[1,2,3,4,5].each(function(w) {  // This will show 5 alert boxes
        alert( w );
    }
);


[1,2,3,4,5].find(function(w) {  // This will return 3
        return w == 3;
    }
);

Placing a breakpoint on the alert( w ); line actually breaks on the entire function. So you can't get into the iterator to see where your issue is. Instead you'll get an error message further down the line in Prototype's method .each. So an easy way to break into the function and see what's happening every iteration is to use debugger; in your JS like so:

[1,2,3,4,5].each(function(w) {  // This will show 5 alert boxes, breaking before each alert
        debugger;
        alert( w );
    }
);


Tip #2: Quick Watch, Add Watch
Yes! You can use Visual Studio's Watch windows to see your JS values, methods, properties, etc... Just break into the debugger and highlight your variable, right-click and select either Add Watch or Quick Watch (or you can just hover over the variable for a second or two). You can then see all methods, properties, values and etc belonging to that object. This helps tremendously when that hard to find JS bug comes up.


Tip #3: AJAX and Web Services
Finally, you can debug your AJAX Web Service calls too! Just use the same methods mentioned above to debug JS and you can step into, over and through all of your JS code, including your ScriptResource.axd and Web Service scripts!

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, May 09, 2007 4:00 PM
Permalink | Comments (1) | Post RSSRSS comment feed

JavaScript and Server Controls

I've been finding quite a few people on the Client-Side forums on ASP.NET asking about how to bridge the gap between JavaScript and ASP.NET. The questions are usually related to getting data, or a variable, from JavaScript to ASP.NET and vice versa. So today I am going to show how to accomplish both tasks, along with some time saving tips. Ok, you know how I roll, let's get started.

Objective #1: Read and Set data to a TextBox Server Control from a JavaScript var

The only two things we'll need here is a TextBox Server Control and an Input button.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="submit" value="JavaScript" onclick="return myScript();"/>

Notice the onclick event of the input button. It's pointing to the myScript() JavaScript function that we have yet to create. Let's do it now.

function myScript()
{
  // Reference to our TextBox1 Server Control
  var txtBox = document.getElementById("<%=TextBox1.ClientID%>");

  // Set
  txtBox.value ="You ran myScript()";

  // Read
  var read = txtBox.value;

  return false;
}

Pay very close attention to the "var txtBox" line. Look at the ID of the element. Now before we go on let me explain why I used <%=TextBox1.ClientID%> instead of the ID TextBox1. For .NET to keep track of all its server controls it generates IDs for each server control based on its heirarchy in the page. If you're looking at this page generated with a MasterPage you would get a different ID for the TextBox. Move the control into a Wizard and you'll get another ID.

Example: The same TextBox control inside a Wizard control looks like

<input name="Wizard1$TextBox1" type="text" id="Wizard1_TextBox1"/>

Notice the ID is now Wizard1_TextBox1. The JavaScript code would throw an error if it were looking for the ID TextBox1 because the .NET engine has rendered the control with a different ID. That's where ClientID comes in. ClientID contains the rendered ID of the server control. So no matter where you move TextBox1 on the page using TextBox1.ClientID will point to the correct element in HTML, and this is precisely what our JavaScript needs. This also saves you a lot of time should you ever want to move your controls around.

Side Note: The ClientID property should be used on Server Controls that implement the INamingContainer. This is to keep all control IDs unique (more here: http://msdn2.microsoft.com/en-us/library/3hc29e2a.aspx).

Continuing on now... Our txtBox variable now points to our TextBox1 server control. We can then set or read the value of the textbox using the next lines of code.

// Set
txtBox.value = "You ran myScript()";

// Read
var read = txtBox.value;

Finally we return false instructing the onclick event to stop any further processing. This stops the button from doing a postback. On the other hand you could return true. In this case the JavaScript code will run and then the form will postback.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by SuperGhost on Tuesday, April 24, 2007 4:00 PM
Permalink | Comments (2) | Post RSSRSS comment feed