You are here:   Blog
Register   |  Login

 

Jul 29

Written by: Michael Washington
7/29/2013 5:47 AM  RssIcon

image

Visual Studio LightSwitch contains an advanced JavaScript data binding framework on par with any of the alternatives that you will find. It has the advantage that it also has an integrated business and data layer. The most important aspect is that it is built into and fully integrated in Visual Studio, the most advanced web development tool available.

image

The example application covered here is simple, but the most important thing to note is that it is simple to create, understand and most importantly simple to refactor.

 

The Application

Note: You can see the live example at: http://lseasejs.lightswitchhelpwebsite.com/HTMLClient/

image

When you run the sample application, you will see a red ball move from the left to the right side of the screen, then start over on the left side when it reaches the right side.

You can change the size of the ball by moving the top slider.

 

image

You can change the vertical position of the ball by moving the bottom slider.

 

image

You can obtain the current position of the ball by clicking on it.

Creating The Application

Set-up EaselJs

image

To make the animation, the sample application uses EaselJs that is part of the CreateJS suite.

image

First, create a LightSwitch HTML Client application and switch to File View.

image

Download the latest EaselJs file and place it in the HTMLClient project in the Scripts folder.

Add a reference to the file in the default.htm page.

When you are done, switch back to Logical View.

 

The Screen

image

Create a new screen.

image

Select Write Code then the created method.

Use the following code for the method:

 

var objScreen;
myapp.Home.created = function (screen) {
    // Set screen to our global Screen property
    objScreen = screen;
    // Set default values
    objScreen.CircleSize = 2;
    objScreen.VerticalPosition = 150;
};

 

image

Add a New Custom Control.

image

Keep the data path as Screen and click OK.

The other custom controls that will be added later will be scoped to specific properties.

image

Change the name of the control to CanvasControl and click the Edit Render Code button to enter the HTML and JavaScript code that will represent the control.

Use the following code for the method:

 

myapp.Home.CanvasControl_render = function (element, contentItem) {
    // Create a Canvas
    var itemTemplate = $("<canvas id='demoCanvas' width='1000' height='300'></canvas>");
    // Set .css for the Canvas
    itemTemplate.css({
        "backgroundColor": "lightyellow"
    });
    // Append the Canvas to the element
    itemTemplate.appendTo($(element));
    // Set-up the Canvas
    initializeCanvas();
};

 

Use the following code to initialize the Canvas:

 

function initializeCanvas() {
    // Get an instance of the Canvas
    objScreen.demoCanvas = $("#demoCanvas")[0];
    // Create a Stage on the Canvas
    objScreen.Stage = new createjs.Stage(objScreen.demoCanvas);
    // Create a Shape on the Stage
    objScreen.Circle = new createjs.Shape();
    // Make the Shape a red circle
    objScreen.Circle.graphics.beginFill("red").drawCircle(0, 0, 40);
    // Set the location of the Shape on the Stage 
    objScreen.Circle.y = 250;
    // Add a handler that will only fire when the shape is clicked on
    objScreen.Circle.addEventListener("mousedown", onCircleMouseDown, false);
    // Add the Shape to the Stage
    objScreen.Stage.addChild(objScreen.Circle);
    // Create a Timer that will fire a method called tick 
    createjs.Ticker.addEventListener("tick", tick);
    // Set the Ticker
    createjs.Ticker.setFPS(30);
}

 

Use the following code for the Tick event:

 

// This event is fired based on the setting for .setFPS(30)
function tick(event) {
    // Move the circle 5 positions
    objScreen.Circle.x = objScreen.Circle.x + 5;
    // The y position is set to whatever the latest value for
    // objScreen.VerticalPosition is
    objScreen.Circle.y = objScreen.VerticalPosition;
    // The circle size is set to whatever the latest value for
    // objScreen.CircleSize is
    objScreen.Circle.scaleX = objScreen.CircleSize;
    objScreen.Circle.scaleY = objScreen.CircleSize;
    // If the Circle moves off the camvas start it over
    // by moving it back to zero
    if (objScreen.Circle.x > objScreen.Stage.canvas.width) {
        objScreen.Circle.x = 0;
    }
    // Update the visuals
    objScreen.Stage.update(event);
}

 

Use the following method to handle the MouseDown event (when the red circle is clicked):

 

function onCircleMouseDown(event) {
    // The Shape (Circle) has been clicked on
    var paramX = event.target.x;
    var paramY = event.target.y;
    // Display the currrent position of the Shape (Circle)
    alert('paramX:' + paramX + ' paramY:' + paramY);
}

 

Data Binding

image

You can learn more about data binding in Visual Studio LightSwitch, and watch a video at this link:

http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/168/Writing-JavaScript-That-Implements-The-Binding-Pattern-In-Visual-Studio-LightSwitch.aspx

(note an updated version of the chapter is in the book: Creating Web Pages Using the LightSwitch HTML Client In Visual Studio 2012)

 

Bind The Sliders

First, we will create a method that will render the sliders and bind them to the value passed to the method.

Click the Write Code button and add the following method:

 

function createSlider(element, contentItem, min, max) {
    // Generate the input element.
    $(element).append('<input type="range" min="' + min +
        '" max="' + max + '" value="' + contentItem.value + '" />');
    // Now, after jQueryMobile has had a chance to process the 
    // new DOM addition, perform our own post-processing
    // (basically for each jQuery Mobile widget, like the slider, 
    // there is a “<controlname>init” event you can listen for 
    // that is called after they have finalized the content of the DOM) 
    $(element).one('slideinit', function (e) {
        var $slider = $(e.target);
        // If the content item changes (perhaps due to another control being
        // bound to the same content item, or if a change occurs programmatically), 
        // update the visual representation of the slider:
        contentItem.dataBind('value', function (newValue) {
            $slider.val(newValue);
        });
        // Conversely, whenever the user adjusts the slider visually,
        // update the underlying content item:
        $slider.change(function () {
            contentItem.value = $slider.val();
        });
    });
}

 

Layout The View Model

This is the part where LightSwitch really shines. It provides a visual representation of the screen we are about to create. LightSwitch uses the MVVM structure for designing applications. The View Model is represented on the left side of the screen designer. This is where we place our properties, collections, and methods.

image

Use the Add Data Item button to add a data item to the screen.

image

Add a property called VerticalPosition.

image

Add a property for CircleSize (integer).

image

Now, drag and drop the VerticalPosition and CircleSize properties from the View Model to the screen designer.

image

Change each control to a Custom Control.

Use the following code for the Render method for each control:

 

myapp.Home.CircleSize_render = function (element, contentItem) {
    // Create a slider bound to this value
    createSlider(element, contentItem, 1, 10);
};
myapp.Home.VerticalPosition_render = function (element, contentItem) {
    // Create a slider bound to this value
    createSlider(element, contentItem, 0, 300);
};

 

Special Thanks

A very special thank you to Stephen Provine.

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have Visual Studio 2012 (or higher) installed to run the code)


Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation