Category Archives: JavaScript

CURRRRGGHHHSSSS

AKA CORS

I thought I had CORS all figured out. Of course, like all things programming, the more you think you know the sooner something is going to blow your world wide open. As a guy who codes for the web a lot, these errors are get under my skin. They’re annoying when you know you put a line of code in your server to allow all origins. They’re even more so annoying when the browser (or framework you’re using) tells you that you CAN’T use a wildcard and just allow ALL origins.

Let me leave this link right here: https://enable-cors.org/index.html

If you’re having CORS trouble on your server, it would behoove you to click that link there and finally be done with it. If you’re using ASP.NET chances are you’re using a Windows server and you’ll be able to use either the ASP.NET or IIS6/7 solutions.

My current favorite method for handling CORS with ASP.NET applications ( especially if you’re using SIGNALR and UseCors(CorsOptions.AllowAll) isn’t what you need, as browsers still puke with this in place )

<system.webServer>
     <httpProtocol>
         <customHeaders>
             <add name="Access-Control-Allow-Origin" value="http://localhost:58547" />
             <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE, TOKEN" />
             <add name="Access-Control-Allow-Credentials" value="true"/>
         </customHeaders> 
     </httpProtocol>
 </system.webServer>

This goes in your web.config with <configuration> as its parent element. You can use a wild card in place of the

"http://localhost:58547"

You CANNOT add another origin to the Access-Control-Allow-Origin. Why? No idea. But if you try, you’ll get an error like this

The ‘Access-Control-Allow-Origin’ header contains multiple values ‘http://localhost:58547, http://wolf-mywebsite.com&#8217;, but only one is allowed. Origin ‘http://wolf-mywebsite.com&#8217; is therefore not allowed access.


 

AngularJS: Single Page Applications with $route

Single Page Applications can easily be created and maintained when using AngularJS. Single page applications are achieved by injecting HTML into the main page (index.html) using the ng-view directive and some routing. The routes will point to partial HTML pages that will be injected into index.html.

Getting Started

Using routing with Angular requires having the angular-route.js or angular-route.min.js files and a reference to one of them inside index.html. They can easily be acquired via NuGet, the AngularJS package includes all the scripts you could ever possibly need for Angular. I’ve also included a reference to an app.js file which will contain the module and route configurations.

singlePageApp_ScriptReferences

The Body

Setting up the body of index.html is extremely easy because it just acts as a skeleton to the partial pages that will be injected in to it.

singlePageApp_BodyOfPage

The body element contains the ng-app directive which has a value that indicates the module name I will use in app.js will be “app”. Within the nav element is a list of links to the partial pages. The href properties’ values use the #/ syntax which refers to the /partials/ directory and is how angular identifies the routes. The #/ syntax is then followed by the name of the page (don’t put the .html extension). Inside the div container is the ng-view directive which tells the page that this is where you want the partials injected into.

Partials

The following is an example of a partial page that can be injected into index.html. The solution explorer on the right side contains all the partials listed from the nav element in index.html.

singlePageApp_HomePageAndSolution

Creating the Routes

The syntax for creating routes in Angular is very simple. A module will need to be created and ‘ngRoute’ will be need be passed into the second parameter – which is an array that takes controllers, services, and factories that the module depends on. After creating the module, the module’s .config property needs to be configured with the routes. The first parameter .config takes $routeProvider and the second parameter takes a function which will also accept $routeProvider as a parameter. Inside the function contain a list of routes. The routes follow the syntax of

$routeProvider.when(‘/pageName(like the links on index.html w/o the #)’,{ templateUrl: ‘partals/pageName.html’});

There is also an option$routeProvider property .otherwhise which allows you to redirect the user to a certain page in the event of something like a link not yet implemented. The syntax is:

$routeProvider.otherwise({ redirectsTo: ‘/pageName’ });

Here is app.js in it’s entirety.

singlePageApp_appDotJs

The final product of all of this will create singe web page which will be able to quickly inject in different partial HTML pages.

The Header and Nav bar remain static on the page, when a link is selected the $routeProvider identifies the correct partial page and the HTML gets injected into the div element that contained the ng-view directive.

singlePageApp_InTheBrowser

singlePageApp_appDotJs2

JavaScript: Review of Objects and Constructors

The next section on codeacademy is called Arrays of Objects, in which I would infer I’m about to create arrays that contain objects. Let’s see if I’m right.

A bit of useful information
An object is seen as just another type of data, such as a string or a number. Anything that you are able to do with other types of data, you can also do with objects. This means you can create arrays of objects.

Creating an Array of Objects

In my previous post about creating custom constructors, we created one called Person which appeared in a few examples. We’re going to continue using this constructor, but this time we get to create an array which contains the Objects we create.

// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}

// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

Creating a loop to run through an array and retrieve data from the objects within.

An array containing objects can be looped through just like any other array containing other types of data.

So the first mission is to create a for loop that will print out the name property of each object in the array. We can use a basic for loop which declares a variable and sets it to 0, we’ll keep the loop running until i <=3, and then we’ll increment i by 1 every time the loop runs.

for(var i = 0; i <= 3; i++ )
{
    console.log(family[i].name);

}

family[i] let’s us move through the arrays values as the loop increments i and the .name tells it to retrieve value that the name property contains.

Passing Objects into Functions

It looks like our versatility with Objects continues to grow, objects can also be used as parameters for functions! This is useful because it allows for functions to utilize the methods and properties the objects provide.

The following example has the Person constructor and creates a new function that calculates the age difference between the two people entered as parameters.

// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}

// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
}

var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

// get the difference in age between alice and billy using our function
var diff = ageDifference(alice,billy);

The objects Alice and Billy are created using the constructor. Remember: Objects are just a type of data like a number or string value. This means we can pass Alice and Billy in as parameters when we call our function to calculate the age difference. Because the properties are still associated with the object when passed into the function, we can specify which property we want to pull data from.

Another example of creating a function and passing in objects as parameters. The following function, appended to the previous example, will return the age of the whoever is oldest.

//Create a function called olderAge
//It will take 2 parameters
var olderAge = function(person1, person2) {
    if(person1.age > person2.age) {
        return person1.age;
    }
    else{
        return person2.age;
    }
}

JavaScript: Arrays of Objects

The next section on codeacademy is called Arrays of Objects, in which I would infer I’m about to create arrays that contain objects. Let’s see if I’m right.

A bit of useful information
An object is seen as just another type of data, such as a string or a number. Anything that you are able to do with other types of data, you can also do with objects. This means you can create arrays of objects.

Creating an Array of Objects

In my previous post about creating custom constructors, we created one called Person which appeared in a few examples. We’re going to continue using this constructor, but this time we get to create an array which contains the Objects we create.

// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}

// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

Creating a loop to run through an array and retrieve data  from the objects within.

An array containing objects can be looped through just like any other array containing other types of data.

So the first mission is to create a for loop that will print out the name property of each object in the array. We can use a basic for loop which declares a variable and sets it to 0, we’ll keep the loop running until i <=3, and then we’ll increment i by 1 every time the loop runs.

for(var i = 0; i <= 3; i++ )
{
    console.log(family[i].name);

}

family[i] let’s us move through the arrays values as the loop increments i and the .name tells it to retrieve value that the name property contains.

Passing Objects into Functions

It looks like our versatility with Objects continues to grow, objects can also be used as parameters for functions! This is useful because it allows for functions to utilize the methods and properties the objects provide.

The following example has the Person constructor and creates a new function that calculates the age difference between the two people entered as parameters.

// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}

// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
}

var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

// get the difference in age between alice and billy using our function
var diff = ageDifference(alice,billy);

The objects Alice and Billy are created using the constructor. Remember: Objects are just a type of data like a number or string value. This means we can pass Alice and Billy in as parameters when we call our function to calculate the age difference. Because the properties are still associated with the object when passed into the function, we can specify which property we want to pull data from.

Another example of creating a function and passing in objects as parameters. The following function, appended to the previous example, will return the age of the whoever is oldest.

//Create a function called olderAge
//It will take 2 parameters
var olderAge = function(person1, person2) {
    if(person1.age > person2.age) {
        return person1.age;
    }
    else{
        return person2.age;
    }
}

 

JavaScript: Creating Custom Constructors

This post is going to be about what I’ve learned throughout codeacademy’s tutorial section on creating custom constructors called ‘Construction Junction’

Custom Constructors: Allows properties to be set for an object upon it’s creation.

  • Custom constructors are useful in reducing the amount of code required when creating Objects.
  • A constructor is basically a template for Objects that allows you to create the Objects and set the values in a very simplistic manner.

Creating a Custom Constructor

The constructor is created by using the function parameter, naming the constructor so you can call it, and the Object will use upon creation.

function Person(name,age) {
  this.name = name;
  this.age = age;
}

Something worth noting is that the keyword “this” is being used here. The “this” keyword is what allows us to create Objects with different names because it calls the properties relative to the current object’s name.

Calling the constructor to create an object

The constructor can now be used to create Person objects, which will reduce the amount of code having to be written.

var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);

The name of the bob object is defined by ‘var bob’
The Person constructor is then called by using the ‘new’ keyword and specifying the constructor: ‘new Person();’
The Person constructor defines two properties, name and age, which are set equal to the parameters provided: (“Bob Smith”, 30); The first parameter here makes bob.name equal to “Bob Smith” and bob.age equal to the value of 30.

When using object constructor notation the code requires 3 lines of code to create each object, where our customer constructor requires only 1 line.

var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;

Imagine if we had an object that had 10 or more properties being stored within it, that would be a lot of lines of code required to be used. By using the custom constructor you can severely reduce the amount of code required.

Here is an example I created that uses 6 properties in the Object. Each Object and it’s properties can be easily defined using one line of code per Object.

function Dog(name, age, breed, color, preowned, disposition) {
    this.name = name;
    this.age = age;
    this.breed = breed;
    this.color = color;
    this.preowned = preowned;
    this.disposition = disposition;
}

//Only one line of code required to create each object, this reduces the total lines of code required 
//even if we're only creating two objects!

var Sunny = new Dog("Sunny", 4, "Pit", "blue", 0, "Happy");
var Killer = new Dog("Killer", 2, "Chihuahua", "brown", 1, "Hostile");

Even when our Object only has 6 properties, the reduction in the lines of code required is impressive. Here the same result achieved by creating the Sunny and Killer Objects using the Object Constructor method

var Sunny = new Object();
Sunny.name = "Sunny;
Sunny.age = 4;
Sunny.breed = "Pit";
Sunny.color = "blue";
Sunny.preowned = 0;
Sunny.disposition = "Happy;

var Killer = new Object();
Killer.name = "Killer";
Killer.age = 2;
Killer.breed = "Chihuahua";
Killer.color = "brown";
Killer.preowned = 1;
Killer.disposition = "Hostile";

Using the Person Custom Constructor, I created the two Objects using 10 lines of code. (blank lines included)
Using the Object Constructor method, we used 15 lines of code. (blank lines included)

5 lines of code between two Objects doesn’t seem big, but if we added one more object then the Custom Constructor method would require one more line of code to add the Object, the Object Constructor would require another 8 lines of code.

How to declare a property without adding it to the constructor’s parameters

In all the previous examples I’ve had all the properties defined using parameters in the Constructor’s function

function constructorName(parameter1, parameter2, parameter3)

We then passed the values into the parameters by defining them when we create each object

var objectName = new constructorName(parameter1, parameter2, parameter3);

By defining the properties using the parameters in this method, it allows us to set different values for the properties for each Object.

What if we wanted to create a property that contained a static value across every Object we create using this constructor?

This can be easily done by declaring the value inside the function with a static value and not creating a parameter value for it. Here is an example using the Person Constructor again in which a property contains a static value.

function Person(name,age) {
  this.name = name;
  this.age = age;
  this.species = "Homo Sapiens";
}

The example above creates a property called this.species in the Object that set to “Homo Sapiens”. So say we create two objects, sally and holden using the above constructor. Since the parameters defined in the Constructor are name and age, these are the only properties we declare when calling it [the constructor].

var sally = new Person("Sally Bowles", 39);
var holden = new Person("Holden Caulfield", 16);

Even though we only declared the name and age properties, sally and holden both contain a third property called species which is equal to “Homo Sapiens” because we defined this value when we created the Constructor.

The properties contained by the Object Sally created using the constructor:
sally.name = ” Sally Bowles”
sally.age = 39
sally.species = “Homo Sapiens” [The property we declared in the Constructor]

The properties contained by the Object holden created using the constructor:
holden.name = “Holden Caulfield”
holden.age = 16
holden.species = “Homo Sapiens” [The property we declared in the Constructor]

Constructors with Methods

So as it turns out, constructors not only have the ability to set the properties of an Object via defining parameters or  declaring them directly in the constructor, Constructors also have the ability to define methods! This allows the Object to have its own methods as soon as it’s created.

Here is an example of defining a method in the constructor. The constructor will contain a method that calculates the area of a rectangle based upon two provided parameters, height and width.

function Rectangle(height, width) {
  this.height = height;
  this.width = width;
  this.calcArea = function() {
      return this.height * this.width;
  };

The method in the example is named calcArea and again, it calculates and returns the area of a rectangle based upon the provided height and width parameters. So when we create an Object using this constructor, there will be a value contained at objectName.calcArea based upon the value returned by the calculation,

You can create a variable and set the value to be equal to that of which was returned by the method in our Object (objectName.calcArea).

var rex = new Rectangle(7,3);
var area = rex.calcArea();

The first line creates an Object called rex using the Rectangle(); constructor we defined above, the value 7 is passed in for height and the value 3 is passed in for width. The method calcArea that was defined in the constructor now takes the two values that were passed in for the constructors parameters and multiplies them to calculate the area of a rectangle. We can therefore create a new variable called area and set it equal to the value returned by method rex.calcArea();

This is the final example that codeacademy provides to illustrate the ease of adding similar objects  as well as how to obtain a value calculated by a method

//This function creates our constructor
function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}

// now we can easily make all of our rabbits
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

//This is how we can invoke a method in our Object. The method in our constructor writes to 
//the console "I am a " + thePassedParameter + " rabbit" which is what is displayed when we call the 
//method.
rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();

This is just a quick run-down on what constructors are and we can do using custom constructors, all in one place.

  • Constructors are used to create objects, one method is to use the Object constructor. The Object constructor becomes tedious however when creating multiple objects and having to add the properties each and every time.
  • We can create our own Custom Constructors in order to set the properties for an Object right when it’s created.
  • Custom Constructors can be comprised of defined parameters, properties with set values, as well as methods.

JavaScript: Creating methods

Wait… What’s a method?

Methods are functions that are used in specifically as part of an Object and is created in basically the exact same way. They allow you to:

  • Change Object property values
  • Make calculations based on object properties. Functions can only use parameters as input, but methods can make calculations with object properties.

In order to create a function you would do something like…

//A function is declared by creating a variable and then setting it equal to function(aVariable);
var timesTwo = function(number)
{
     return number*2;
}
//This is how the function is called and a value gets passed into it
timesTwo(2);

The code is saying you want to create a variable called timesTwo which is a function and it takes input called number. The function will take whatever ‘number’ is return it’s value after being multiplied times two.

In order to create a method, you define what Object you want the method to branch from and then define the name of the method itself by using objectsName.methodName. 

//This is the object being declared and it has a property called occupation
var Grim = new Object();
Grim.Occupation = Reaper;

//This is how the method is created - Just like a function.
//Grim's occupation is pretty... grim, so this will let us change it.
Grim.setOccupation = function(newOccupation) {
     Grim.Occupation = newOccupation;
}
//here we call the method and change Grim's job to Flower Delivery!
Grim.setOcccupation("Flower Delivery");

Methods have the ability to be used for multiple Objects, not just one. This means that if I wanted give Hades a new occupation instead of being the lord of the underworld, I could! The trick to get a method to be used for more than one type of object is to use the keyword “this”

//Here is Grim again
var Grim = new Object();
Grim.Occupation = Reaper;
//Here is Hades, written slightly different but with the same effect.
var Hades = {
     Occupation: "Ruler of the UnderWorld, dun dun dunnnn"
};

//This is the method that will let us change their occupations
//Instead of saying Grim.setOccupation, we name ONLY the method and then use the "this" keyword inside it. 
//This lets us use it for more than one type of Object.
var setOccupation = function (newOccupation){
     this.Occupation = newOccupation;
};

Grim.setOccupation("Flower Delivery");
Hades.setOccupation("Professional balloon crafter");

The keyword “this”, if used inside of a method that has the Object declared alongside it, can be used as a placeholder solely within the method. “What’s the use of that?” you say, well, if you have a complicated name for your function or if you just want to cut time off typing – it can help a lot!

var thirdRectangle = new Object();
thirdRectangle.height = 1;
thirdRectangle.width = 2;

thirdRectangle.setWidth = function (newWidth) {
     this.setWidth = newWidth;
}

Methods, like functions, allow you to return values from them

square.sideLength = function() {
     return this.sideLength * this.sideLength;
}

JavaScript

So not to long ago before I started looking into ALM I was working on learning JavaScript by using CodeAcademy.org. CodeAcademy is a great tool for learning how to write code in an interactive tutorial that requires nothing more than an internet connection and a browser.

Currently I’m sitting at 61% done of the JavaScript tutorial there and it’s been extremely informational. It’s been a while since I’ve done some of the tutorials however, so I’m rereading through all my notes as i’m starting off again.

Here’s a preview of what it looks like taking the tutorial on CodeAcademy. It’s extremely intuitive and makes learning Code pretty awesome. I totally recommend this site to anyone interested in learning code by themselves.

CodeAcademyPreview