Javascript default parameters

"use strict";

// no IE support
// no Safari support

function doSomething(a = 1, b = 2) {
	console.log(`a=${a}`);
	console.log(`b=${b}`);
}

doSomething(); // 1, 2
doSomething(10); // 10, 2
doSomething(undefined, 20); // 1, 20
doSomething(10, 20); // 10, 20
doSomething(null, null); // null, null

// default value can be a function call, like an argument exception:
function go(val = missingValue("val")) {

}

function missingValue(paramName) {
	throw new Error(`Parameter ${paramName} is missing`);
}

try { go(34); console.log("ok"); } catch (ex) { console.log(ex); } // ok
try { go(); console.log("ok"); } catch (ex) { console.log(ex); } // error message

Send AWS SES email with javascript

Using the node-ses package:

"use strict"; 

var ses = require('node-ses'),
    client = ses.createClient({  
        key: 'mykey',  
        secret: 'mysecret' , 
        amazon: "https://email.us-west-2.amazonaws.com"
    }); 

// Give SES the details and let it construct the message for you.  
client.sendEmail({ 
    to: 'someone@example.com', 
    ,from: 'someone@example.com', 
    , cc: 'someone@example.com', 
    , bcc: ['canbearray@example.com, 'someone@example.com'] 
    , subject: 'Test Message ' + new Date() 
    , message: 'your <b>message</b> goes here' 
    , altText: 'plain text' 
    }, function (err, data, res) { 

        if (err) { 
            console.log("ERROR"); 
            console.log(err); 
        } else { 
            console.log("Done"); 
        } 
    }
);

Replace alert with SweetAlert

SweetAlert is a nice simple solution for displaying alert messages. Here’s the basic way to replace the built-in alert, so you don’t have to use the custom swal function:

<link href="/styles/sweetalert.css" rel="stylesheet" type="text/css">   
<style type="text/css">
   .sweet-alert h2 { font-size: 21px; font-weight: 500; line-height: 23.1px; }
</style>

<!-- SweetAlert does not work in IE8 or prior -->
<!--[if gt IE 8 | !IE]><!-->
   <script src="/scripts/sweetalert.min.js" type="text/javascript"></script>
   <script type="text/javascript">
       window.alert = function () {
           if (arguments == null) {
               swal(" ");
           } else if (typeof arguments[0] === "number") {
               swal(arguments[0].toString());
           } else {
               swal(arguments[0] || " ");
           }
       };
   </script>
<!--<![endif]-->

Queue and Stack in javascript

Using basic array functions, you can treat an array as a queue (first in first out) or a stack (last in first out);

To act as a queue, use the shift function:

while (arr.length) {
  let val = arr.shift();
  console.log(val);
}

To act as a stack, use the pop function:

while (arr.length) {
  let val = arr.pop();
  console.log(val);
}

Handlebars in NodeJS

"use strict";

(function() {
    const handlebars = require("handlebars");
    const source = "{{title}}\n"
        + "Hello {{person.name}}, I see that you are {{person.age}} years old.\n"
        + "You have the following cars:\n"
        + "{{#each cars}}\n"
        + "    {{year}} {{make}} {{model}} {{#if color}}(Color={{color}}){{/if}}\n"
        + "{{/each}}\n";

    const template = handlebars.compile(source);
    const data = {
        title: "My Data Object",
        person: { name: "Billy", age: 34 },
        cars: [
            { year: 2015, make: "Ford", model: "Mustang", color: "Red" },
            { year: 2014, make: "Chevy", model: "Corvette" },
            { year: 2013, make: "Dodge", model: "Aries", color: "Yellow" }
        ]
    };
    const result = template(data);
    console.log(result);
})();

/****** OUTPUT *******
My Data Object
Hello Billy, I see that you are 34 years old.
You have the following cars:
    2015 Ford Mustang (Color=Red)
    2014 Chevy Corvette
    2013 Dodge Aries (Color=Yellow)
******* OUTPUT ******/

AJAX in Angular

Regular GET/POST:

$http({
    method: "POST",
    url: "someUrl",
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    },
    data: JSON.stringify({ name: "John Doe" })
}).then(function(response) {
    console.log("Successful response: " + response);
}, function(response) {
    console.log("Error response: " + response);
});


JSONP (in a factory)

// Make sure you include it in DI:  app.factory("myFactory", function ($http, $sce) {
factory.getSomething = function (callback) {

    const URL = "http://something.../?param=someval¶m2=otherval";

    var url = $sce.trustAsResourceUrl(URL);

    $http.jsonp(url, {
        jsonpCallbackParam: "callback"
    }).then(function (response) {
        console.log("Successful response: " + response);
    }, function (response) {
        console.log("Error response: " + response);
    });
};
/*
response:
    data – {string|Object} – The response body transformed with the transform functions.
    status – {number} – HTTP status code of the response.
    headers – {function([headerName])} – Header getter function.
    config – {Object} – The configuration object that was used to generate the request.
    statusText – {string} – HTTP status text of the response.
*/

JSONP with jQuery and ASP.NET

JSONP allows you to execute something similar to AJAX, across domains without worrying about whether the request is across domains, or any special CORS configuration.

It’s not generally a huge deal to set up CORS, but JSONP is guaranteed to work in all browsers and servers without any special handling.

Javascript

function go() {
    jQuery.ajax({
        // url: "/Home/DoSomething", // Regular MVC
        // url: "/Handler1.ashx", // WebForms
        data: {xyz:"World"},
        dataType: "jsonp",
        type: "get"
    }).done(function (result) {
        console.log(result);
    });
}

ASP.NET

// Regular MVC - no special filters, return types, etc. 
public ActionResult DoSomething(string xyz) 
{
    Response.ContentType = "application/json";
    var foo = new { FirstName = "John", LastName = "Doe", Message = "Hello " + xyz };
    Response.Write(string.Format("{0}({1});", Request["callback"], JsonConvert.SerializeObject(foo)));
    return null;
}

// WebForms
public class Handler1 : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        var foo = new { FirstName = "John", LastName = "Doe", Message = "Hello " + context.Request["xyz"] };
        context.Response.Write(string.Format("{0}({1});", context.Request["callback"], JsonConvert.SerializeObject(foo)));
    }

    public bool IsReusable { get { return false; } }
}

jQuery noConflict

If you need to inject a specific version of jQuery into a webpage that may or may not already have a different version of jQuery, or if you specifically need two different versions loaded, then you can use jQuery.noConflict.

You might use this if you’re building a custom control that gets injected into a page, where you want to make sure your stuff works as intended, but you don’t want to accidentally upgrade or downgrade the main page’s jQuery.

Sample Code

This sample will show how to load jQuery 1.8.3 into a page which may or may not already have a different version loaded.

var _jq183;

function load183() {
    if (typeof window.jQuery === "function" && window.jQuery.fn && window.jQuery.fn.jquery === "1.8.3") {
        _jq183 = window.jQuery;
        return;
    }

    if (typeof window.jQuery === 'undefined' || !window.jQuery.fn || (window.jQuery.fn.jquery !== "1.8.3")) {

        var done = false;

        var body = document.getElementsByTagName("body")[0];
        var scr = document.createElement("script");
        scr.setAttribute("src", "https://code.jquery.com/jquery-1.8.3.min.js");
        scr.onload = scr.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                done = true;
                _jq183 = jQuery.noConflict(true);
                scr.onload = scr.onreadystatechange = null;
                body.removeChild(scr);
            };
        };
        body.appendChild(scr);
    };
}

function showVersion() {
    if (typeof $ === "undefined") {
        console.log("$ is undefined");
    } else {
        console.log("$: " + $.fn.jquery);
    }
    if (typeof jQuery === "undefined") {
        console.log("jQuery is undefined");
    } else {
        console.log("jQuery: " + jQuery.fn.jquery);
    }
    console.log("_jq183: " + (_jq183 ? _jq183.fn.jquery : "N/A"));
}

You may get an error message, like:

Refused to load the script 'https://code.jquery.com/jquery-1.8.3.min.js' because it violates the following Content Security Policy directive: "script-src somethingsomething.com".</code>

From what I’ve read, if you get this, you’re out of luck because the site won’t allow you to inject a script from another domain.

jQuery Filter by Data

jQuery won’t let you search using a regular selector for data attributes if those data attributes were added using the data function:

jQuery("#something").data("somekey", "someval");
jQuery("#something[data-somekey=someval]"); // does not find it

Instead, define a new function:

jQuery.fn.filterByData = function(prop, val) {
    return this.filter(function() { 
        return jQuery(this).data(prop) == val;
    });
};

jQuery("#something").filterByData("somekey", "someval"); // finds it

StackOverflow question: http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value

Stackoverflow answer: http://stackoverflow.com/a/15651670/111266

jQuery AJAX

I’m sure there’s a perfectly good explanation for why the “always” function has two different signatures – one for requests that were successful and a different one for unsuccessful ones. But whatever their reason, they’re wrong. This is just plain stupid that you don’t know what kind of object the first and third parameters are. But they never asked me before they implemented it, so there’s nothing I can do about it…

var jqXHR = jQuery.ajax(ajaxParams);
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown ) { });
The ajaxParams object contains lots of different options - the ones I generally use are as follows:
{
    // absolute or relative
    url: "/path/to/some/url",

    // will you be receiving "json", "html", "text", or "xml" back
    // 99% of the time I use json or html. If json, then the result will already
    // be parsed into a javascript object.
    dataType: "json",

    // what kind of data you are posting
    // 'application/x-www-form-urlencoded; charset=UTF-8' is the default
    contentType: "application/json; charset=utf-8",

    // This one is fun. If you're posting form-urlencoded, then this can 
    // either be a string representing the form post, like name=John&age=34
    // or it can be a javascript object and jQuery will automatically build
    // the string: { name: "John", age: 34 }
    // However, if you are posting JSON, then it needs to be a JSON string (not
    // an object, but the JSON representation of that object):
    // JSON.stringify({ name: "John", age: 34 })
    data: myData
}

There’s a lot more you can do with it – see the documentation.