So what is this – javascript

To the uninitiated this can be really confusing in JavaScript. Consider the following:

image

The code above logs this three times, but what is this?

The main source of confusion is a quirk of the language where depending on the invocation pattern this can be set to the global variable (e.g. window in a browser). But there are come other gotchas.

In the example above this is 3 different objects.

  • Window
  • ATest
  • Object

Function Invocation Patterns

In order to explain this we need to know what function invocation patterns are in JavaScript, of which there are 4.

  • method
  • function
  • constructor
  • apply/call

I’ve covered the first 3 above in my example

Method

image In the method invocation patters, the method is called bare. Javascript assigns the global variable to this in this instance.

Constructor

imageIn this constructor invocation pattern (i.e. new) this is assigned to the object getting created, ATest 

Function

image In the function invocation pattern this is the enclosing type also, however this is just object in this case i.e. the object literal returned from ATest constructor.

Apply

I’m not covering this here but the Apply (and the call) invocation patterns basically let you set the value of this.

Note: Object Literal can be avoided in this example above as follows.
What we do is set the methods on this explicitly.

image

 

Angular.js .NET File Upload

In this post I’m going to show you how to upload a file using Angular.js on the client side and Asp WebApi on the back end.

Lets get started

Create you project in visual studio, and add your angular.js app controllers etc.

Interestingly enough I’ve already shown you how to do the server side over 2 years ago!
Crikey 2 years and I’m still writing about the same old stuff….. well not really, last time it was knockout, sliverlight and the likes, now it’s Angular.js’ turn.

Angular file upload, Nuget

In order to facilitate the process, we’re going to use a nuget package I like, see screenshot.

image

The beauty of this package is that its got shims for non html5 browsers (apparently there are a few hanging around still :-( )

To use this package you’ll need to include 2 scripts, file-upload-shim before angular.js and file-upload after.

Script Includes

image


Markup

Next add the input tag and add the ng-file-select directive

image

 

Javascript

Module

Add the upload module

Factory

image

Here i added the $upload factory to my controller

Controller function

image

Here I enumerate the files (should i wish to have multi select) then I upload each one by posting to my Web Api .net controller, I pass a little more information also as to the diff side, but that’s pretty much it.

.NET

Now even though I did show you the .net code before I’m going to show it again now, because as I mentioned I’m passing a little information as to the side the file I’m uploading represents.

image

image