Re-Learning Backbone.js – Models

Over the past few days I’ve started to re-learn Backbone.js. It’s been a good while since I have worked with it. One of the many resource that I used during this endeavor is the post that I created January of this year. Understanding Backbone.js – Simple Example

Since I’m re-educating myself on Backbone.js, I thought this would be a good opportunity to Blog about the process I’m going through while re-learn Backbone.js again. In this post I will present the concept of Backbone.js Model.

So here I go again.

Based on past experience, I believe creating an application on Backbone.js there’s are few key concepts that should be understood: Model, View, Collection, Template and Router.

The first thing we are going to do is create a Movie class and instantiate an instance of the movie. Nothing fancy, this should be very simple. This Movie class will be based on a Backbone.js Model. JavaScript does not support classes, but here we will simulate a class.

Movie Sample 1

Movie Sample 1


    Movie Sample 1

Close Bitnami banner

The code above is creating a Movie class from Backbone.Model.Extend. When an object is created from the Movie class the intialize function should be called and the message “Movie Model Created” should be written to the console.

If you load this page in a web browser, I’m using chrome, the results should be displayed in the console.

There is a problem here, everything is a global variable. Since we will be creating many Models, Views, Collections and templates, lets create a place to organize these structures.

var MovieApp = {
	Models: {},
	Collections: {},
	Views: {},
	Templates: {}

MovieApp.Models.Movie = Backbone.Model.extend({
	initialize: function () {
		console.log("Movie Model created");

var movie = new MovieApp.Models.Movie();

Continue reading “Re-Learning Backbone.js – Models”

Understanding Backbone.js – Simple Example

I’m by no means an expert in Backbone.js.  I created this post because I had difficulty understanding backbone, and I hope that the information that I provide will help others grasp Backbone.js a little faster.  This post is directed to individuals who understand the concepts of Backbone.js, but are having a difficult time implementing a simple solution.

This post provides a simple example on Backbone.js Routers, Models and Collections and Views.  I’m going to try to make this example extremely simple. But also show key Backbone.js concepts

I’m probably not the best writer.  It would take me days, if I were to validate all the grammar, spelling and such.  So I’m just going to try to get it done.  Even though the grammar and such may not be perfect, the technical parts of the article should be correct.  I hope you enjoy.

A few months after writting this post, my priorites and technology direction changed. For probably 6 months I did little work with Backbone.js. When I came back to Backbone.js in November, I was a little lost. I had to become familar with the technology once again. I thought it would be a good opportunity to write about Backbone.js basics. Here are posts where I describe the basics of Backbone.js.

This post will be based on a contrived idea of displaying a list of movies at a theater.
Continue reading “Understanding Backbone.js – Simple Example”

JavaScript: FireFox – Support for IE outerHTML

I have a web page that calls a Web Service.  The Web Service returns HTML.  This HTML need to be updated in the web page.  This is a fairly easy process in IE:  obj.outerHTML = new HTML.  But, I also need to get this to work in Firefox.  At first I had a difficult time creating a solution, but after a little Googling and understanding range and createContexualFragment the pieces started to fall together. This is what I came up with.. 


SetOuterHTML(newHtml, obj) {

   if (obj.outerHTML) {

    obj.outerHTML = newHtml;



      var r = obj.ownerDocument.createRange();


      var df = r.createContextualFragment(newHtml);

      obj.parentNode.replaceChild(df, obj);

How to read inner/outerHTML with NN6?

Introduction to Range

The Four Different inner/outer text/html Combinations

InnerHTML for Mozilla(See "View the entire Source" at bottom of page)

createContextualFragment( )

JavaScript String.IsNullOrEmpty

I’ve been doing a lot of JavaScript lately and in my JS I’ve been testing if a string is empty, null or undefined.   C# has string.IsNullOrEmtpy and I believe JS should have the same.  I was about to write my on function, but decided to first see if someone else has done this.  I found an example, but didn’t completely like it. So I made some changes and here’s String.IsNullOrEmpty
 String.IsNullOrEmpty = function(value) {
  var isNullOrEmpty = true;
  if (value) {
   if (typeof (value) == ‘string’) {
    if (value.length > 0)
     isNullOrEmpty = false;
  return isNullOrEmpty;
I don’t know why it’s "String.IsNullOrEmpty" instead of "String.prototype.IsNullOrEmpty", but it works.  Maybe someone can answer this for me.

JavaScript IE FireFox onload

There are problems with FireFox using onload.  Most of the documentation and articles that I have read identifies that FireFox does not support onload.  I currently have FireFox 3 installed and onload seems to work.  But I have not been able to test onload on previous versions of FireFox.
I’m probably going to have to implement a solution for previous version of FireFox.  I have found some good reference of doing onload with previous version of FF, but do not have time to implement it right now.  I’m just going to put the references here so I can find them later.
BWCJP posted the following code at
I believe the latest version of fire fox and likely the previous version require ‘document’ and not window as thats for IE and Opera accepts window also
//set page event handlers
if (window.attachEvent) {
  //IE and Opera
  window.attachEvent("onload", Page_Load);
  window.attachEvent("onunload", Page_Unload);
} else {
  document.addEventListener("DOMContentLoaded", Page_Load, false);
  document.addEventListener("unload", Page_Unload, false);
Firefox IE7 onload event question
The window.onload Problem – Solved!

Passing Dictionary From JavaScript to ASP.NET Web Service

The ASP.NET project that I’m currently working on uses AJAX to save data to a Web Service.  The web service is generic.  The web page should be able to pass address, phone numbers, sales info and etc to the web service.  Base on the key that is also passed to the web service, the web service should know how to save the data.
The first version of the client code that called the web service gathered all the data from the form and created a string that was pipe delimited.  Example: key=person|keyid=333323|firstname=John|lastname=Handcock.   When this information arrives at the web service it must be parsed and saved. A lot of red flags seem to pop up with this design.
Here’s the web service signature or the first version
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=false)]
public string Save(string input)
There will always be a few fields that will be passed (key and keyID) to the web service.  The problem is that data fields (firstname, lastname, address and etc) could be different.  I figured out that I could add .NET Dictionary type to as a parameter to web service call.  The problem now is how do I gather and pass this information from the client javascript.
Here’s the the new save method web service
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=false)]
public string Save(string key, string keyID, Dictionary<string, string> inputNameValue)
I could use the following JavaScript to pass data to the web service and it works, but the data values (first, last) need to be created dynamically. 
MoFormSave.Save(key, keyID, {"first":"john","last":"handcock"})
I tried to create an array that accepts an NameValue object and pass the object to web service, but this errors when I call the web service.  I finally figure out I could do the following and pass the object to the web service.
   var nameValue = {}; //new, empty object
   nameValue[‘first’] = ‘John’;
   nameValue[‘last’] = ‘Handcock’;
   MoFormSave.Save(key, keyID,  nameValues)
Quick guide to somewhat advanced JavaScript – tour of some OO features

JavaScript Modal While Processing

On the current ASP.NET project that I’m working on, I’m using AJAX to save the user input to a WebMethod(WebService).  While the save is running the user needs to be prompted that their data is being save.  At this time the user should not be able to do any other action on the page until the save has completed. 
Below are the resource that I used to solve this problem. All the resources but the first were fairly complex.  The first resource did a very good job of  solving my problem.  I listed the other resource because they provided some additional information.
Modal-style pops in Javascript and CSS (The simplest and it works; works in IE7 and FireFox 3)
Lightbox Gone Wild (JavaScript Libary) (Looks fairly complex)
Javascript Modal Dialog Tutorial (Discusses issues that browses have)
Modal Dialog Box – modalDialog.js (JavaScript Library)

When Leaving Page, Prompt The User That Changes Have Not Been Saved

I’m in the process of create a few input forms in ASP.NET (Name, address, and etc).  If the user makes a change to the page and tries to navigate away from the current page without previously clicking save, the current page should prompt the user that there are changes to the page and does the user want to continue to navigate to a different page.  The prompt should be triggered by any of the following:  selecting a link, closing the window, entering a new URL in the address bar, selecting back, hitting refresh or other means. 
To solve this problem I first tried using onunload, but could not find any way of stopping the user from going to another page.

[sourcecode language=”xml”]
body onunload=”ConfirmExit”

After a little research I found a method window.onbeforeunload.  window.onbeforeunload provides the developer a way to notify the user that there has been changes that have not been save before navigating to a different page.  In the following example I use ASP.NET instead of strait HTML.  The code behind loops through every webcontrol that’s in the form and wires up the control’s onchange JavaScript event to call InputChange function. If the user changes any of the controls the isDirty variable is set to true. 
As you can see in the following code the window.onbeforunload is set to ConfirmExit function. This is the part that is used to notifies the user. Any time the user tries to exit the page the ConfirmExit function will be called.  In the ConfirmExit function, if the isDirty variable is true, the user should be prompted with a message to confirm if they want to leave the page.  If isDirty is false the the user is redirect without a prompt.  
If the user clicks save button, I do no not want him to be prompted that the data has not been save. So I set the following for the button control.

[sourcecode language=”javascript”]

I tested the following code and confirm it works in IE7 and FireFox 2.0

[sourcecode language=”csharp”]
public partial class TestPromptSave : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
if (Page.IsPostBack == false) {

private void SetupJSdataChange(Control parentControl) {
foreach (Control control in parentControl.Controls) {
//Response.Write(control.ID + “<br>”);
if (control is WebControl) {
WebControl webControl = control as WebControl;
webControl.Attributes.Add(“onchange”, “InputChanged(this)”);
protected void Page_Save(object sender, EventArgs e) {

HEre some more

[sourcecode language=”xml”]
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”TestPromptSave.aspx.cs” Inherits=”TestPromptSave” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>
<html xmlns=””>
<head runat=”server”>
<title>Untitled Page</title>
<body >
<script type=”text/javascript” language=”javascript”>
var isDirty = false;
window.onbeforeunload = ConfirmExit;

function InputChanged(control)
isDirty = true;
function ConfirmExit()
if(isDirty == true){
return “You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?”;


<form id=”form1? runat=”server” >
<a href=”RedirectPage.aspx”>RedirectPage.aspx</a>
<br /><br />
First Name
<asp:TextBox ID=”txtFirstname” runat=”server” />
Last Name
<asp:TextBox ID=”txtLastName” runat=”server” />
<asp:DropDownList ID=”ddlState” runat=”server” >
<asp:ListItem Text=”" Value=”" />
<asp:ListItem Text=”CO” Value=”CO” />
<asp:ListItem Text=”TX” Value=”TX” />
<asp:ListItem Text=”FL” Value=”FL” />
<asp:ListItem Text=”OK” Value=”OK” />
<br />
<asp:Button ID=”butSave” runat=”server” Text=”Save” OnClientClick=”isDirty=false” onclick=”Page_Save” /> &nbsp; | &nbsp;
<asp:Button ID=”butCancel” runat=”server” Text=”Cancel” />

MSDN – onbeforeunload Event
4 Guys From Rolla.Com – Prompting a User to Save When Leaving a Page
The IE OnBeforeUnload Event Handler
Reminding Users to Submit Forms
IE runs onbeforeunload twice for no reason?
Warn users about unsaved changes in a web form