by Andreas

Define a #Region in javascript files (Visual Studio 2010 / 2012)

In these times of super responsive client side processing mega javascript extravaganza web applications  you’re more than likely to end up with fairly large .js files in your projects. The standard code file in Visual Studio allows you to define collapsible sections by wrapping them with the #region / #endregion blocks. In javascript files however, you are restricted to collapsible functions only (“#region” is not recognized as anything valid):

image

Well, I just found out that that’s not entirely true. By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable

image

by Njål

Force Hard Reload in Chrome

Reloading pages in Chrome can be done in a few different ways:

  • Ctrl-R (or F5) – Normal Reload
  • Ctrl-Shift-R (or Ctrl-F5) – Hard Reload

I’m sure you knew this already. But here’s a new trick – you can do a Hard Reload and Clear Cache at the same time by right clicking on the Reload button. This requires that you have the developer console open (F12).

image

by Njål

String replaceAll in Javascript

imageIn Javascript the string.replace(“target”, ”replacement”) function only replaces the first occurrence of the target…

Here’s how you can add a replaceAll() metod to all Strings (similar to Extension Methods in C#).

String.prototype.replaceAll = function (orig, replacement) {
    return this.split(orig).join(replacement);
}

 

You can then write (anywhere in your code):

"a a b c".replaceAll("a","X"); //==> "X X b c"
by Andreas

KnockoutJS – how to force binding refresh / re-evaluation

Observable bindings in KnockoutJS get re-evaluated when the focus is changed in a form, for instance when you click a button or use TAB to move from one input field to the next. When KnockoutJS is used in combination with an ASP.NET panel control where a DefaultButton is defined, re-evaluation of observable bindings is not performed when the user clicks ENTER to trigger the button click event. As a result of this, a value entered in an input field that is bound to the view model will not be registered if the user doesn’t navigate (move focus) away from the field first. 

A work-around for this is to use jQuery (or pure javascript) and programmatically set the focus to a different control, for instance the button itself when the event is fired.

self.addNewTimeRegEntry = function () {
    // set focus to button control to force re-evaluation
    $("#<%= btnAddRegEntry.ClientID %>").focus();

    ... // continue as normal

The button click event is bound to the addNewTimeRegEntry function above (through the KnockoutJS framework), and by moving the focus all variables will be refreshed before further processing is done.

by Stian

Redirect page with jQuery / JavaScript

There are several different ways to do a clean redirect from one URL to another with some simple jQuery / javascript. I’ll start out here showing what in my opinion is the best way to simulate a HTTP redirect and then show a few other options that you have.

Pure javascript
// similar behavior as an HTTP redirect
window.location.replace("http://blog.degree.no");

This method is in my opinion the best, because the window.location.replace() is redirecting the page without putting the original page in the browser history.

// similar behavior as clicking on a link
window.location.href = "http://blog.degree.no";

This method works fine as well, but it will throw the user in to a back button loop if they would want to go back in history.

jQuery

My impression is that developers sometimes search for the “jQuery way” to do things and maybe you found this blog post searching for “redirect page with jQuery”? While there is a way to do this in jQuery, there is really no reason why you would want to do this as it could not be easier to with normal javascript. But since you searched for it, here it is.

$(location).attr("href",http://blog.degree.no);

 

image

by Andreas

Converting JSON date string to javascript date object

JSON dates come in a format that isn’t directly convertable to Javascript date objects (e.g. /Date(1349301600000+0200)/ ). This can cause a bit of headache, but there is a very simple way to convert this to a native date object.

After stripping off the initial “/Date” part using substr, parseInt will return only the integers and ignore the trailing “/”. The result is an integer value that can be used in the native javascript Date constructor.

This is what goes on under the hood:

1. Original JSON date

/Date(1349301600000+0200)/

 

2. After substr(6)

1349301600000+0200)/

 

3. After parseInt()

1349301600000

 

Finally I am using DatePicker from the jQuery UI library to format the date to a custom JSON date:

// parse JSON formatted date to javascript date object
var date = new Date(parseInt(jsonDate.substr(6)));

// format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", date);

 

On the server side I recommend using the Json.NET framework by James Newton-King (available as a NuGet). It contains several settings for handling dates depending on what you’re running client side. If you’re using KnockoutJS for instance, the ko.toJSON method will return your date object in UTC format (which means the date might suddenly be a day off, with an offset set to +2 hours my current timezone).

My quick-fix using DateTime.ToLocalTime() will work, but I am sure there is a more elegant way of getting your local time directly in the Json deserialization process:

// parse JSON
var timeRec = JsonConvert.DeserializeObject<JSONTimeRecord>(jsonString, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// convert date to local time
updatedRecord.Date = timeRec.Date.ToLocalTime();

 

At least that works fine – for now..

by Njål

console.log and Internet Explorer

imageWhen coding/debugging JS I usually work with Chrome and console.log works like a charm. But when you test the same page in Internet Explorer you’ll get a javascript error.

If you then open Developer Tools in IE and hit refresh – the page will work 100% – since IE now has a console object (the developer tools window) it can log to.

The solution is to either remove all console.log statements – or add this at the top of your js file:

 

if console === undefined {
    console = { log : function(){}};
}

 

 

by Joakim

Bundling of CSS and JavaScript in MVC 4 Beta

MVC 4 Beta comes with support for bundling (and minification) of CSS and Javascript out of the box which is pretty neat.

By adding link- and script-tags like the ones below, you will you get the content from all the css- or js-files in the given directories minified and bundled together into a single resource, or will you?

<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>

I added a custom css-file to “~/Content/”, as well as a custom js-file to “~/Scripts/” and expected them to become part of the resource bundles automagically, however that was not the case at all! So what gives?

It turns out that the method “BundleTable.Bundles.RegisterTemplateBundles();”, which is called under “Application_Start” in “Global.asax.cs”, contains hardcoded values for which resources that should be added to the bundles (default files such as site.css, jquery.cs, etc).

However, if you replace “BundleTable.Bundles.RegisterTemplateBundles();” with “BundleTable.Bundles.EnableDefaultBundles();” things work like you would expect them to. The latter actually looks in the specified directory and finds all the css- and js-files which is them minified and bundled together. If you ask me, this should have been the default used in the “MVC 4 Web Application”-template.

Another way to have all the files included in your bundles is to create and add them to the bundle collection yourself like so:

protected void Application_Start()
{
    Bundle styles = new Bundle("~/MyStylesBundle", new CssMinify());
    styles.AddDirectory("~/PathToMyStyles", "*.css");
    BundleTable.Bundles.Add(styles);

    Bundle scripts = new Bundle("~/MyScriptBundle", new JsMinify());
    scripts.AddDirectory("~/PathToMyScripts", "*.js");
    BundleTable.Bundles.Add(scripts);
}

Note! Since MVC 4 is still in beta, this may change (hopefully it does)!

by Stian

How to do a raffle ticket draw in javascript

I would like your help on how to do a raffle ticket draw using JavaScript. I am throwing out a suggestion and  hope that you will try to improve or accept this code by using the comment field below (that is if you are human enough to beat the captcha!)

function Draw(){
    var tickets=["Andreas","Andreas","Andreas","Andreas","Andreas","Andreas",
    "Andreas","Andreas","Andreas","Andreas","Andreas","Andreas",
    "Thor Halvor","Thor Halvor","Thor Halvor","Thor Halvor","Thor Halvor",
    "Thor Halvor","Thor Halvor","Thor Halvor","Thor Halvor","Njål","Njål",
    "Njål","Njål","Aage","Aage","Aage", "Stian", "Stian", "Stian","Stian","Joakim"];
  
    var winner = Math.floor(Math.random()*tickets.length);
    alert("The winner is: " + tickets[winner]); 
}


I would recommend using a website like http://jsbin.com to write up and test your script

by Njål

RequestReduce: Combine & Compress resources. Like a boss.

Combres is a very popular framework for the .NET platform to combine and minimize css/javascript files. Installation is pretty easy using nuget, and configuring it usually isn’t too bad either.

But be ware – there is a new kid on the block: RequestReduce. This is even easier to use, and also compresses external javascript files you might have referenced through CDNs etc.

Install using Nuget, and hit refresh in your internet browser twice. That’s it. RR automatically detects your javascript/css and takes care of the rest:

 

<link href=”/RequestReduceContent/9d8e9e90e8de050baf2bc2df819f5211-e6cc9b875d6351964ba7d5c434007001-RequestReducedStyle.css” rel=”Stylesheet” type=”text/css” />

<script src=”/RequestReduceContent/03a7e950cff059d0608ab101ee08b178-4f5e2f27d36f2cf9ebaae1acfe4f4f40-RequestReducedScript.js” type=”text/javascript” ></script>