4/29/08

How to create a class in JavaScript

It turns out that JavaScript does not really support classes - weird... But there is a way to create them. Since everything is a function, create functions that that you need. Think of them as your class private methods. Start by creating a function that represents the constructor. In the constructor create methods and properties that connect to the private functions and variables using the assignment operator.

For example:


//privates
var firstName;
var lastName;
var isAdmin;
var hours = 0;


//constructor
function Worker(var workingHoursAWeek)
{
//passes personsAge to private var hours
hours = workingHoursAWeek;
//creates properties
this.FirstName = firstName;
this.LastName = lastName;
this.Hours= hours;
this.IsAdmin = isAdmin;


//create a method
this.IsBusy = isBusy;
}


//private function
function isBusy()
{
return (hours > 40) ? true : false;

}
Store the code in a separate .js file.
To use the class, include it in your .htm file
by passing it to scr



<script type="text/javascript" src="Worker.js"></script>

Now you can create an object and use it's properties and methods:

Worker denis = new Worker(40);
denis.Hours += 5;
if (denis.IsBusy) alert("help!");

_________________________________________________________

It is always great to see a working sample. Here I am going to use the exercise 11.16 from Deitel's "Internet & World Wide Web - How to program", which strangely does not show you how to create a class in JavaScript.
_________________________________________________________



Step 1. create a new JavaScript file "AirplaneReservationSystem.js" with the following code:



var SIZE;
var FIRST_CLASS_LIMIT;
var seats;

function AirplaneReservationSystem(size, firstClassLimit)
{
SIZE = size;
FIRST_CLASS_LIMIT = firstClassLimit;
seats = new Array(SIZE);
for(var i = 0; i < seats.length; i++)
seats[i] = "empty";
this.ReserveEconomy = reserveEconomy;
this.ReserveFirstClass = reserveFirstClass;
this.Seats = seats;
this.IsFull = IsFull;
}

function reserveEconomy()
{
var seat = -1;
for( var i = FIRST_CLASS_LIMIT; i <= SIZE; i++)
{
if(seats[i] == "empty")//if there are seats available
{
seats[i] = "full";
seat = i + 1;
i = SIZE;
}
}
return seat;
}

function reserveFirstClass()
{
var seat = -1;
for( var i = 0; i < FIRST_CLASS_LIMIT; i++)
{
if(seats[i] == "empty")
{
seats[i] = "full";
seat = i + 1;
i = FIRST_CLASS_LIMIT;
}
}
return seat;
}


function IsFull()
{
for(var i = 0; i <>(seats[i] == "empty")
return false; //found a seat
return true; //plane's full
}

Step 2.
create and .htm file where you can use the above class. Here is the code for it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Excercise 11.16</title>
<script type="text/javascript" src="AirplaneReservationSystem.js"></script>
<script type="text/javascript">

    var SIZE = 9;
var FIRST_CLASS_LIMIT = 5;
var airplane = new AirplaneReservationSystem(SIZE, FIRST_CLASS_LIMIT);
var seat;
function ReserveSeat()
{
if(airplane.IsFull())
alert("Airplane is full");
else //reserve a seat
{
if(form.ticket[0].checked)//First Class
{
window.status = "Reserving First Class ticket...";
seat = airplane.ReserveFirstClass();
if(seat != -1)
window.status = "Reserved a seat number " + seat + " in FirstClass.";
else //first class is full
{
if(confirm("Can we try to place you in Economy?")==true)
{
seat = airplane.ReserveEconomy();
window.status = "Reserved a seat number " + seat + " in Economy.";
}
else
alert("Next plane leaves in 3 hours");
}
}
else if(form.ticket[1].checked)//Economy
{
window.status = "Reserving Economy ticket...";
seat = airplane.ReserveEconomy();
if(seat != -1)
window.status = "Reserved a seat number " + seat + " in Economy.";
else //economy is full
{
if(confirm("Can we try to place you in First Class?") == true)
{
seat = airplane.ReserveFirstClass();
window.status = "Reserved a seat number " + seat + " in FirstClass.";
}
else
alert("Next plane leaves in 3 hours");
}
}
else
alert("Select ticket type before reserving the seat");
}
}

</script>
</head>
<body>
<form name="form" action="">
<h1>Airline Reservation System</h1>
<br />
<br />
<p>
<input type="radio" name="ticket" value="FirstClass"/>
<label>First Class</label>
<br />
<input type="radio" name="ticket" value="Economy"/>
<label>Economy</label>
<br />
<br />
<input type="button" value="Reserve Seat" onclick="ReserveSeat()" />
</p>
<br />
<br />
<label>Result: </label>
<input name="Result" type="text" />
</form>
</body>
</html>

4/17/08

databind WPF controls sample

It's pretty simple:
Set the controls data context to the object that has the data, then bind specific properties.
Lets assume that you have a class User that has a property IsActive and you want to bind a checkbox to user.IsActive:

In code set the data context (note you can limit the scope to a particular control).

this.DataContext = user;

bind in XAML:
<CheckBox IsChecked="{Binding Path=IsActive}"/>


Here's a sample that has a simple user control with a couple of textboxes and checkboxes that use databinding to display data. The control pretends to need some user info. It stores it in one of its properties "CurrentUser". Once the property is populated it, the controls will display it:

























First lets create a data container in the form of a class "User".



namespace BindingSample
{
public class User
{
public int Id { get; set; }
public bool IsActive { get; set; }
public bool IsAdmin { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
}



Then lets create a XAML UserControl - the main thing to note here is the binding code (in yellow):



<UserControl x:Class="BindingSample.formUser"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Border CornerRadius="5" Margin="50" Background="White">
<Border.BitmapEffect>
<OuterGlowBitmapEffect GlowColor="LightGray"/>
</Border.BitmapEffect>
<StackPanel>
<!-- header -->
<Grid Background="#8AA37B" Opacity=".85">
<StackPanel Orientation="Horizontal">
<Label Foreground="White" FontSize="12">u s e r</Label>
</StackPanel>
</Grid>
<!-- body -->
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="69*" />
<ColumnDefinition Width="70*" />
<ColumnDefinition Width="35*" />
<ColumnDefinition Width="35*" />
<ColumnDefinition Width="35*" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="1" HorizontalContentAlignment="Right" Margin="5" Foreground="#435D36" FontSize="12">login</Label>
<StackPanel Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal" FlowDirection="RightToLeft">
<Label Content="{Binding Path=Id}" Foreground="#458B00" FontSize="12"></Label>
<Label Foreground="#435D36" FontSize="12">id</Label>
</StackPanel>
<Label Grid.Row="1" Grid.Column="1" HorizontalContentAlignment="Right" Margin="5" Foreground="#435D36" FontSize="12"&gt;first name</Label>
<Label Grid.Row="2" Grid.Column="1" HorizontalContentAlignment="Right" Margin="5" Foreground="#435D36" FontSize="12">last name</Label>
<Label Grid.Row="3" Grid.Column="1" HorizontalContentAlignment="Right" Margin="5" Foreground="#435D36" FontSize="12">email</Label>
<Label Grid.Row="0" Grid.Column="2" Margin="5" Content="{Binding Path=UserName}" Foreground="#458B00" FontSize="12"></Label>
<TextBox Grid.Row="1" Grid.Column="2" Margin="5" Text="{Binding Path=FirstName}" Grid.ColumnSpan="3" BorderBrush="#8FA880" FontSize="12"></TextBox>
<TextBox Grid.Row="2" Grid.Column="2" Margin="5" Text="{Binding Path=LastName}" Grid.ColumnSpan="3" BorderBrush="#8FA880" FontSize="12"></TextBox>
<TextBox Grid.Row="3" Grid.Column="2" Margin="5" Text="{Binding Path=Email}" Grid.ColumnSpan="3" BorderBrush="#8FA880" FontSize="12"></TextBox>
<StackPanel Orientation="Horizontal" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="4" Margin="5" FlowDirection="RightToLeft">
<CheckBox Margin="0,5,15,5" BorderBrush="Transparent" Background="Transparent" FlowDirection="RightToLeft" IsChecked="{Binding Path=IsAdmin}" FontSize="12" >admin</CheckBox>
<CheckBox Margin="0,5,5,5" BorderBrush="Transparent" Background="Transparent" FlowDirection="RightToLeft" IsChecked="{Binding Path=IsActive}" FontSize="12" >active</CheckBox>
</StackPanel>
</Grid>
</StackPanel>
</Border>
</UserControl>



In control's code, lets create a property CurrentUser, there we can set the data context:


namespace BindingSample
{
/// <summary>
/// Interaction logic for formUser.xaml
/// </summary>

public partial class formUser : UserControl
{
private User currentUser = new User();

public formUser()
{
InitializeComponent();
}

public User CurrentUser
{
get { return this.currentUser; }
set
{
this.currentUser = value;
this.DataContext = currentUser;
}
}
}
}
Next step is to create a window and instanciate the control that was created above: (create a new XAML file) and add the control:



<Window x:Class="BindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingSample"
Title="Window1" Height="300" Width="300">
<Grid>
<local:formUser x:Name="formUserDetail"/>
</Grid>
</Window>


And in code behind, lets populate the user and pass it to the control:

namespace BindingSample
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>

public partial class Window1 : Window
{
private User user;

public Window1()
{
/*create a user*/
user = new User();
user.Id = 987;
user.IsActive = false;
user.IsAdmin = true;
user.UserName = "denism";
user.FirstName = "denis";
user.LastName = "morozov";
user.Email = "denis.morozov@this.com";

InitializeComponent();

this.formUserDetail.CurrentUser = user;
}
}
}