Javascript OO with Object Notation

I’ve been digging into javascript more and more to provide a better client side user experience in my asp.net mvc applications.  To help facilitate this, I have some Html.Helper objects that accept javascript functions.

A confusing part of javascript to someone that is a novice is that javascript functions act like, ie. C# functions.  However, javascript functions are ‘objects’

Some of my initial code then is just pure functions, ie.

function  billRateError(XMLHttpRequest, textStatus, errorThrown) {
                var errMsg = "<P>Error Loading: " + XMLHttpRequest.responseText  + "<br/>";
                $("#addStatus").html(errMsg).show();
            }
function billRateSubmitting(formData, jqForm, options) {
    var loading = "<img src=’" + BuildUrl("Content/Images/spinner.gif") + "’>";
    $("#addStatus").html(loading).show("slow");
}
function billRateResponse(response, statusText)  {
        $("#addStatus").html("").show();
        $("#billRatesDiv").html(response).show();
}

Basically I’d have a page ‘BillRate.ascx’ with a corresponding javascript file ‘BillRate.js’ – sorta like a ‘code-behind’.

Within my page I have my helper helper, ie.

<% Html.jQueryAjaxOptions("addBillRateForm", AjaxDataType.html, new Hash(
   target => "’#billRatesDiv’", beforeSubmit => "billRateSubmitting",
   success => "billRateResponse", Error => "billRateError")); %>

(This helper wraps up my jQuery ajax calls)

My next line of thinking though is – ‘let’s move this to a ‘page object’ that handles all the javascript used on that page that is unique to the page.

To do this I use the following javascript OO syntax:

var billRateObj = {
    "target" : "’#billRatesDiv’",
    OnRequest : function(formData, jqForm, options) {
        var loading = "<img src=’" + BuildUrl("Content/Images/spinner.gif") + "’>";
        $("#addStatus").html(loading).show("slow");
    },
    OnResponse : function(response, statusText) {
        $("#addStatus").html("").show();
        $("#billRatesDiv").html(response).show();
    },
    OnError: function(XMLHttpRequest, textStatus, errorThrown) {
        var errMsg = "<P>Error Loading: " + XMLHttpRequest.responseText + "<br/>";
        $("#addStatus").html(errMsg).show();
    }
};

And then I update my Helper:

<% Html.jQueryAjaxOptions("addBillRateForm", AjaxDataType.html, new Hash(
   target => "billRateObj.target", beforeSubmit => "billRateObj.OnRequest",
   success => "billRateObj.OnResponse", Error => "billRateObj.OnError")); %>

I really like this better – it’s all encapsulated.

I’d like to know – is this approach a good approach ?  So far I’ve seen a bit of both.  I also have seen some articles where the programmer doesn’t put the method inside the object.  Maybe it’s my C# background, but I like that encapsulation that it provides.

Let me create some very small examples:

Hybrid Constructor/Prototype:

ie. here is a good way to use the javascript:

MyObject = function(){};

MyObject.prototype.SayHello = function(){
    alert(‘hello’);
}

what is nice here is that ‘SayHello’ isn’t created every time you create MyObject – but rather it is it’s own object (functions are objects in javascript)- and it’s attached to the MyObject. 

This does require this sort of call to it:

new MyObject().SayHello();

Object Notation:

MyObject = {
    SayHello : function(){alert(‘hello’);}
};

Then to use it:

MyObject .SayHello

Comments – recommendations?

UPDATE: Here is a jQuery ‘HowTo’s’ writeup on ‘Javascript Object Notation’ and ‘Anonymous functions‘ : both are showing the use of object notation with objects and functions.

Mozilla Prism

Mozilla Prism, formally know as ‘WebRunner’ provides the capability to run your web application, ‘as an application’.

Prism is a simple XULRunner based browser that hosts web applications without the normal web browser user interface. Prism is based on a concept called Site Specific Browsers (SSB). An SSB is an application with an embedded browser designed to work exclusively with a single web application. It doesn’t have the menus, toolbars and accoutrements of a normal web browser. Some people have called it a "distraction free browser" because none of the typical browser chrome is used. An SSB also has a tighter integration with the OS and desktop than a typical web application running through a web browser.

(from Mozilla Wiki: Prism)

image

Prism is an application that lets users split web applications out of their browser and run them directly on their desktop.

image

image image

They are accessible with Control-Tab, Command-Tab, and Exposé, just like desktop apps. And users can still access these same applications from any web browser when they are away from their own computers.

So what browser ‘engine’ is Prism using?

Prism isn’t a new platform, it’s simply the web platform integrated into the desktop experience. Web developers don’t have to target it separately, because any application that can run in a modern standards-compliant web browser can run in Prism. Prism is built on Firefox, so it supports rich internet technologies like HTML, JavaScript, CSS, and <canvas> and runs on Windows, Mac OS X, and Linux.

Great!  Basically I can develop my application with great tools such as Firebug,  and then deploy my application to the desktop, which then helps ensure it will run as expected.  (I typically make sure my app runs on Firefox/Internet Explorer/Safari anyway).  With FireFox 3.1+ we’re going to see some great new features as well (ie. Offline support which enables web applications to provide offline functionality) – for developers see ‘Firefox 3 for Developers

At first I was trying this out with the new Google Chrome, but a bug in select / combo boxes put it on hold.  The customer basically wants to run their intranet web application in a window that is self contained, without the ‘overhead’ of toolbars, other links, etc…

So, I ran across Prism and setup my test webapp by creating 2 files:

webapp.ini

then creating a ‘zip; of the webapp.ini, naming it <yourAppName>.webapp  (for example: MyApp.webapp )

With Prism installed, you can double click on the .webapp

So, what is Prism then?

Unlike Adobe AIR and Microsoft Silverlight, we’re not building a proprietary platform to replace the web. We think the web is a powerful and open platform for this sort of innovation, so our goal is to identify and facilitate the development of enhancements that bring the advantages of desktop apps to the web platform

Ok, so that is nice, what does it get you?

It includes a simple ‘installer’ that can create all the shortcuts needed -so the user doesn’t need to know URLs.  Also, it gives the ability to control what the user can and can’t do with the browser window – for example, handling ‘forward’ and ‘back’ buttons.

(names removed for now)

image

The .ini can define these properties:

[Parameters]
id=unique-app-id@unique-author-id.whatever
uri=http://localhost/MyApp/Home.mvc
status=yes
location=no
sidebar=no
navigation=no

Here is an example dialog to create the shorcuts to your application:

image

No registry settings, etc… it’s merely creating the shell to run your web application in here.

Chrome user’s might notice – ‘hey this is already built into Chrome’ – which Mozilla recognizes that:

We’re also thinking about how to better integrate Prism with Firefox, enabling one-click “make this a desktop app” functionality that preserves a user’s preferences, saved passwords, cookies, add-ons, and customizations. Ideally you shouldn’t even have to download Prism, it should just be built into your browser. 

We’re working on an extension for Firefox that provides some of this functionality. For more information about the user experience we hope to achieve in Prism, see Alex Faaborg’s blog post.  (I like his future shot image here) For some of the technical details and new features found in Prism, see Mark Finkle’s blog post.

 

(Update : Firefox addon available)

Prism has made it easy to not need to create the .ini / .webapp – simply download and install Prism and run it.  You’ll be greeted with this prompt:

image

I like options, and this is
to me, some very innovative and creative ways to run web applications from the desktop, in particular for intranet based application where you want a level of control over the browser and user experience in that environment.

 

UPDATE: http://labs.mozilla.com/2008/03/major-update-to-prism-first-prototype-of-browser-integration/

Today we’re releasing a major update to Prism that includes new desktop integration capabilities and simpler installation. With this update, you can now get Prism simply by installing a small extension to Firefox 3. With the new Prism extension for Firefox 3, users can now split web applications directly out of Firefox without needing to install and manage a separate Prism application. Just install the extension, browse to a web app, then select Tools > Convert Website to Application.

Other new or improved features include:

  • Pick an icon to represent a web app on the desktop: Prism can use the web app favicon or the user can pick a custom image to represent the web app.
  • Run each web app in its own profile: Prism now places each web app into its own process/profile so they don’t interfere with each other, which also makes it possible to install a web app twice and use it simultaneously with two different user accounts.
  • Badge the dock icon: Initial support for adding a badge to the desktop icon has been added. Currently, this can be done through a custom webapp.js file. We’re working on creating and reusing web standards to expose this to content without requiring custom scripts.

ASP.NET MVC Beta – Ajax

I was noticing the asp.net mvc walkthrough has a section on the Beta1 ajax using the Microsoft ajax library.  Although I’m a big fan of jQuery, these two libraries now come with the framework and can be used together quite well.

In the walkthrough the code samples show a simple call to a controller which returns a string.  Let’s take that a step forward and show how it can return different types using the ‘ActionResult’.

First, make sure you include the scripts in your page – I suggest including them in the head of the master page – in the sample this is under Shared/Site.Master.

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
        type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
        type="text/javascript"></script>

 

(note: in the walkthrough, they are a bit outdated, it should now point to the Scripts folder, not the Content folder – which is what is recommended, as well as a part of the project template install)

Here is the sample – they have added this to the HomeController:

public string GetStatus()
{
    return "Status OK at " + DateTime.Now.ToLongTimeString();
}

public string UpdateForm(string textBox1) { if (textBox1 != "Enter text") { return "You entered: \"" + textBox1.ToString() + "\" at " + DateTime.Now.ToLongTimeString(); }

return String.Empty; }
 

In step one of this, I’m going to go ahead and make a change – where I prefer to return an ActionResult here.

Since it’s just returning a string, we can return using ‘Content’. Here is an example:

 

image

Adding Ajax Helpers to The View

The Mvc framework comes with several new Ajax helpers, the two I’m going to use here from the walkthrough  is the Ajax.ActionLink and the Ajax.BeginForm.  There are named identical to the Html.ActionLink and Html.BeginForm (previously this was called ‘Form’ – now in Beta1 it’s BeginForm)

Let’s look at the ActionLink:

<%= Ajax.ActionLink(“Update Status”, “GetStatus”, new AjaxOptions{UpdateTargetId=”status” }) %>

By default, since the the container view is the ‘Home/Index’, it will look for the Action on the HomeController called ‘GetStatus’.  In the AjaxOptions – it is defining the target for the return of the GetStatus action. In this sample it is a span  with id of ‘status’ : <span id=”status”>No Status</span>  This can be a span, div, etc…  Since we have told ‘GetStatus’ above to return ‘Content’ – it will return a string and place the result in the span element.

I prefer the syntax for the helpers that is included in the Microsoft.  You’ll need to get this ‘futures’ assembly separately (here – you can learn more about it at the bottom of Scott Guthrie’s blog post on the beta1) and include it in the references as well as add a the following to the ‘namespace’ section of the web.config:

<add namespace=”Microsoft.Web.Mvc”/>

(personally I wish they would have just included it in the install… but you know how it is… lol)

So, for some reason they didn’t include the same syntax for the Ajax helpers as they did the Html helpers, the strongly typed ActionLink, ie. <%= Html.ActionLink<HomeController>(c => c.GetStatus(), “Update Status”)%>

This is preferred by me, hopefully they will include it, if not… well, I’ll make another post on how to build your own  🙂

Let’s get back on track.

When we run the application, we will see the following:

image

Clicking ‘Update Status’ makes a call back to the Action – asynchronously:

image

What is happening is that the helper control is creating the link in the html using the asp.net ajax library, looking at the source, you’ll see the following:

<a href=”/Home/GetStatus” onclick=”Sys.Mvc.AsyncHyperlink.handleClick(this,

new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace,

updateTargetId: ‘status’ });”>Update Status</a>

 

Let’s take a brief look at the code here and how we can include some events to the Ajax.ActionLink,

the screenshot below shows the available ‘AjaxOptions’:

image 

Let’s add some functionality and handle the 2 most common events, the ‘OnBegin’ and ‘OnSuccess’:

 
image
 
 

The ‘OnBegin’ is going to handle the event fired before the actual ajax call is made, and the ‘OnSuccess’

will let us handle when the call is done (note: always handle the ‘OnFailure’ as well, in case of any errors!)

In my example I’m adding ‘OnRequest’ and ‘OnResponse’ – these are javascript functions, let’s look here:

 
image 

When the link is clicked, an alert box will open, when it’s done, you’ll get a second alert box. As you might notice I’ve included the ‘content’ in the OnResponse. Using Firebug, we can look at the object in detail:

 
image
 

We can see the xmlHttpRequest object and it’s request to the action ‘GetStatus’. I’m not going to go into more detail into the asp.net ajax library, but you can read more here

I should note, a good way to handle your own validation in javascript is to make validation calls in the ‘OnBegin’ – and if you want to stop the ajax call from continuing, you can return false.

So, let’s go ahead and show a similiar example with a Ajax.BeginForm, as with above, I’m converting the sample that returns a string, to return an ActionResult, using return Content(…):

image

In the view, I’m using the Ajax.BeginForm – (note that I’m wrapping it in a using statement, which I consider to be the best practice):

image

I’ve included handlers for the OnComplete, OnBeing, and OnFailure:

image

(I did manage to sneak in some jQuery goodness, using the $(“#textBox1”) to get the textBox1 element’s value)

Let’s make a minor adjustment here!  Let’s say I want to return some content, outside of ‘just a string’ ?  What I do on my project is have the ActionResult return a control.  Let’s set this up for our grand finale:

Step One:

Create a new Ajax.ActionLink: (you can do this with a form)

image

Step Two:

Create the action on the controller (home):

image

Step Three:

Create a ‘MVC View User Control’ (ascx):

image

image

Step Four:

Add some content to the control:

image

As I show, you can add a model to this control, etc… if you want to see that let me know.

Now, let’s run this add see what our result is:

We added the link at the bottom:

image

When it get’s clicked, it makes an asynchronous call, and then updating just the ‘status’ span (partial page update):

image

This is, imo, much more efficient and clean, then let’s say an ‘UpdatePanel’ in Webforms.  I have full control over the page.  The addition of the asp.net ajax libraries with ajax helpers really helps make this simple to use but extremely powerful.

Example available

The ‘Flavors’ of ASP.NET

Back a year ago when I was preparing for my Monorail presentation at CINNUG (see Monorail: part Ipart II – in particular part II), it was greatly impressed on me that Monorail sat on top of ASP.NET, just like WebForms sits on top of ASP.NET. The key being that Webforms does not equal asp.net – WebForms != ASP.NET

ASP.NET has a great design to it, as it is a the underlying ‘pipeline’, handling the HttpRequest/HttpResponse, and all the core stuff like Authentication, Authorization, Session, Caching, etc.

WebForms, Monorail, MVC, Dynamic Data, etc… all sit on top of asp.net.  This is brilliant, as I’m able to incorporate different parts and pieces – ie. when mvc first came out, I was able to progressively upgrade parts of my webform project – in a hybrid manner.  Some pieces I didn’t really want to upgrade, as it worked fine – other parts made it cleaner and easier to test and maintain.  It made refactoring possible.

Scott Hanselman has been pushing this message, and I’m glad to see it.  In this blog post "Plug-In Hybrids: ASP.NET WebForms and ASP.MVC and ASP.NET Dynamic Data Side By Side" he outlines this:

I wanted to write this post because there seems to be a lot of confusion about how ASP.NET WebForms, MVC and Dynamic Data all fit together. Folks may have WebForms applications and want to start looking at ASP.NET MVC but aren’t sure if they need to start from scratch or not. Folks might look at Dynamic Data but mistakenly assume it’s just for scaffolding administrative sites.

You can (and should) feel free to have Hybrid applications. You can have single Web applications that have all of these inside them (if it makes you happy):

  • ASP.NET MVC
  • ASP.NET WebForms
  • ASP.NET Web Services (ASMX)
  • WCF Services
  • ASP.NET Dynamic Data
  • ASP.NET AJAX

I hope this helps and it’s more clear now that it’s just "an ASP.NET application."

You can feel free to mix and match. Not everyone can (or should) rewrite an existing ASP.NET application, so it is nice that everyone can use some new features in the same ASP.NET application as their existing functionality.

I think all of this is very interesting, and the more one grasps what ‘asp.net’ is – the best underlying of how all of these different ‘frameworks’ work.

The 'Flavors' of ASP.NET

Back a year ago when I was preparing for my Monorail presentation at CINNUG (see Monorail: part Ipart II – in particular part II), it was greatly impressed on me that Monorail sat on top of ASP.NET, just like WebForms sits on top of ASP.NET. The key being that Webforms does not equal asp.net – WebForms != ASP.NET

ASP.NET has a great design to it, as it is a the underlying ‘pipeline’, handling the HttpRequest/HttpResponse, and all the core stuff like Authentication, Authorization, Session, Caching, etc.

WebForms, Monorail, MVC, Dynamic Data, etc… all sit on top of asp.net.  This is brilliant, as I’m able to incorporate different parts and pieces – ie. when mvc first came out, I was able to progressively upgrade parts of my webform project – in a hybrid manner.  Some pieces I didn’t really want to upgrade, as it worked fine – other parts made it cleaner and easier to test and maintain.  It made refactoring possible.

Scott Hanselman has been pushing this message, and I’m glad to see it.  In this blog post "Plug-In Hybrids: ASP.NET WebForms and ASP.MVC and ASP.NET Dynamic Data Side By Side" he outlines this:

I wanted to write this post because there seems to be a lot of confusion about how ASP.NET WebForms, MVC and Dynamic Data all fit together. Folks may have WebForms applications and want to start looking at ASP.NET MVC but aren’t sure if they need to start from scratch or not. Folks might look at Dynamic Data but mistakenly assume it’s just for scaffolding administrative sites.

You can (and should) feel free to have Hybrid applications. You can have single Web applications that have all of these inside them (if it makes you happy):

  • ASP.NET MVC
  • ASP.NET WebForms
  • ASP.NET Web Services (ASMX)
  • WCF Services
  • ASP.NET Dynamic Data
  • ASP.NET AJAX

I hope this helps and it’s more clear now that it’s just "an ASP.NET application."

You can feel free to mix and match. Not everyone can (or should) rewrite an existing ASP.NET application, so it is nice that everyone can use some new features in the same ASP.NET application as their existing functionality.

I think all of this is very interesting, and the more one grasps what ‘asp.net’ is – the best underlying of how all of these different ‘frameworks’ work.

ASP.NET MVC Beta Released

Inching forward, the ASP.NET MVC goes beta!  So far, this framework has been great to work with!

Read up on Scott Guthrie’s blog of all the details.  Long live MVC!  🙂

From Scott’s blog, a breakdown:

The ASP.NET site has resources available, including, videos, tutorials, quickstarts – and a sample storefront application