• Broadcasting AngularJS events from vanilla JavaScript

    Broadcasting AngularJS events from vanilla JavaScript

    In this short post I’ll show how to invoke AngularJS from plain JavaScript. Why would you want to do this? Well, in certain edge cases you might need to catch events in plain JS but still want to handle them back inside your Angular app. For example on an SVG element mouse event..

    Say you have an Angular controller named SomeCtrl and that’s where you want to handle the event. You’ll need an element you’ll be able to target either by an id or by a class, and it needs to be scoped with a controller like this:

    Next, say you have something like onmouseover=”onMouseOver()” on one of your HTML/SVG elements:

    You’ll need to add a $scope.$on listener for the “mouse-over-event” event inside your SomeCtrl controller. Your Angular app will catch the broadcast, you’ll be back inside the Angular scope and digest loop and you’ll be able to handle the event further from there.

    That’s it!

  • Multi-character Google Maps cluster marker labels

    Multi-character Google Maps cluster marker labels

    Turns out Google Maps API does not allow for more than a single character on marker labels (everything past the first character gets trimmed). Not even stackoverflow was able to provide me with a good way of going around this (take a look at this and this). So, a little digging was required…

    Fortunately, folks who made google-maps-clustering-csharp were able to go around this restriction by implementing a custom “label element” through prototyping the OverlayView element and then using it instead of a string for Marker’s label property. I extracted and cleaned up the code from their MVC application. What’s left is all you need to render markers that support multiple characters (feel free to break it into multiple files – perhaps a service and a controller if you’re using AngularJS or something similar):

    And this is the CSS that’s needed to make it all work (you can find the cluster icons here):

    Cheers!

  • Diving into Gulp

    Diving into Gulp

    For some time now I’ve been waiting to learn how to Gulp properly. As I started working on a home pet-project to keep sharp and get more in-depth with certain things, this was a good opportunity to learn more about Gulp as well. So far, I have mostly been using either famous-ish premade gulp scripts or the tools that came built-in (or as an extension) with Visual Studio. But that never really felt right, more like a cheap get-away.

    Anyway, I went through JavaScript Build Automation With Gulp.js. It’s a Pluralsight ~5hr course by John Papa who is quite a famous name within Angular circles for his angular-styleguide. I loved every bit of the course. It’s easy to follow, goes through the whole setup, explains the how’s and why’s and gives you code samples. I highly recommend it as it will give you a very solid gulp foundation and will make you more productive.

    Right now I’m in the middle of bootstrapping his gulp-patterns, and I’m taking out the stuff that I don’t need. Great base, and I feel very happy about the whole thing. :)

  • Resolving Angular $http promises in services vs. controllers

    Resolving Angular $http promises in services vs. controllers

    For some time now I’ve been asking myself one thing when it comes to resolving $http promises in Angular – “would it be a better practice to resolve them in services that make the calls or in controllers that call these services?”. I always simply went with whatever was the practice on the current project as I didn’t want to introduce inconsistencies into the project. Well I finally set down, played around with it a bit and gave it some active thinking. Turns out, the answer is hugely dependent on the context and there is no right or wrong way to do it but I’ll explain how I decided to do it from now on.

    This post is not about basic usage of $http, then, success, error, callbacks or promises in general. For that I recommend a very nice blog post by dwmkerr.

    Now, one “sub”-question I had here was should I use then or success. Although I noticed a lot of people seem to dislike using success and error callbacks because their signatures are inconsistent with the then callback (they are only a thin wrapper around it), I actually find it very useful that I don’t have to extract the “data” from the response object on my own. If I need to do something like that I still have the option of falling back to using then (which is fine). Some people seem to be really bothered by this so they even go as far as to wrap their responses in new promises using $q to match the then signature, but as Rick Strahl wrote – in this case I don’t really mind trading a bit of inconsistency for simplicity. I don’t see a point in adding additional chunk of wrapper-code to every API call just for the sake of it. So, I decided to go with the success/error combination.

    Back to the main question.. I never make any $http requests directly from controllers and along with any additional “client-side business logic”, that code goes into services. As a rule of thumb, I decided to go with a very simple approach. Since most often what happens after the success callback kicks in is controllers concern, my services return $http promises. Success promises are then resolved from within controllers. If there really is a need (and if it’s logical) to resolve the success callback in the service i will then do it there instead. The whole thing looks something like this:

    Now you’re probably wondering – what about the error callbacks? I could think of a couple of different scenarios of what could go wrong here:

    1. Unhandled exceptions
    2. 404’s
    3. “Expected exceptions” such as unauthorized (401), forbidden (403) or anything else you might knowingly return from the back-end
    4. Back-end model validation (I decided to go with 422 for this)

     

    To make my life easier, for the first three I decided to go with an http-interceptor-service which is in charge of handling WebAPI exceptions. This way I don’t have to rewrite the same error callback code for every $http request. It’s nice, centralized and provides enough flexibility (assuming you’re taking good care of your WebAPI and return proper http statuses).

    As for the last, fourth case, I created a couple of directives that wrap html input elements (text, textarea, dropdown..), WebAPI model state and validation messages (which have the format of foundation abide). For this to work, model state is needed inside a controller and since $http treats 422 status code as an error so far this was the only situation where I had to resolve the error callbacks inside controllers. In this case the http interceptor simply skips any 422 it encounters and it can then be taken care of elsewhere. I will explain this in more detail in my next-next post. Pinky swear. ;)

    The explained might not be the best way to cope with the whole problem but I it worked well for me so far so I hope I was at least able to provide a couple of useful ideas. I did try to google out other blog posts / SO threads about this but I only found a few ones that dealt with something similar but not entirely. If you know of any good ones, please feel free to drop a link down in the comments. Also, if you have a different approach which works for you or you see any problems with mine, do let me know! :)

    Cheers!

  • Automatic WebAPI property casing serialization

    Automatic WebAPI property casing serialization

    If you work a lot with WebAPI’s and JavaScript and would like to follow the convention of lowerCamelCasing your JSON and UpperCamelCasing your .net model properties, you can do that by using Newtonsoft.Json CamelCasePropertyNamesContractResolver. This works for both directions “WebAPI -> client” and “client -> WebAPI” so that’s cool as well. You should simply set this up in your Global.asax and you’re good to go.

    Well that was an easy one. It was also my chance to try out the Gist GitHub ShortCode plugin. I think it works great, and it’s easier to use. I like it! And if you’re using WP, you should try it as well. Hopefully if won’t take me too long to migrate everything from the Code Colorer plugin that I’ve been using so far. :)

  • Dynamically resolving function shared arguments in JavaScript

    Dynamically resolving function shared arguments in JavaScript

    Sometimes we have functions which expect the same arguments as other functions, all fine there. Sometimes these arguments are obtained/resolved asynchronously. If there are a lot of these functions that share the same resource, we can come up with lot of unnecessary boilerplate.

    Imagine having a function like resolveMetaData() which asynchronously obtains fresh data every time it’s called (to keep the code at a very simple level, for the purpose of this post I’ll be using setTimeout() instead of something a bit more complex like an AJAX call):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function resolveMetaData(callback) {
        // for the purpose of the demo we'll simply mock the metaData object    
        var metaData = { message: "Meta message", start: new Date() };

        // async business logic example
        setTimeout(function () {
            metaData.end = new Date();
            // after metaData is ready, resolve callback
            callback(metaData);
        }, 1000);
    }

    And two functions that require a new instance of metaData upon their execution:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function fnOne(data, metaData) {
        console.log(data);
        console.log(metaData);
    }

    function fnTwo(id, data, metaData) {
        console.log(id);
        console.log(data);
        console.log(metaData);
    }

    The simplest way to provide the latest metaData to these functions would be to use callbacks like this:

    1
    2
    3
    4
    5
    6
    7
    resolveMetaData(function(metaData) {
        fnOne("fnOne", metaData);
    });

    resolveMetaData(function(metaData) {
        fnOne(1, "fnTwo", metaData);
    });

    If you had to write a lot of functions similar to fnOne() and fnTwo() (ie. 10 or more) and all of them required the latest metaData, you would most probably be tempted to somehow reduce the code and get rid of the callback boilerplate. The first two ideas that came to my mind on how to resolve this were function overloads and/or having a base function that would handle metaData resolving. Since JS doesn’t really support overloading (in the same way as say C# does), having a base function to handle metaData resolving seems like a safe bet. The only question is – how do we call a function in JS with the parameters we got and resolve the shared parameters asynchronously?

    Fortunately Function.prototype.apply() comes to the rescue! It allows us to call a function with arguments as an array which is quite handy. Since functions in JS are objects, we can now create a base function which accepts the function object of the function we wish to call, and the args we have at that point. It then resolves metaData, appends it to the arguments array and calls the passed function with these arguments. This is how the base function would look like:

    1
    2
    3
    4
    5
    6
    function fnBase(fn, args) {
        resolveMetaData(function (metaData) {
            args.push(metaData);
            fn.apply(this, args);
        });
    }

    And this is the how we can now call fnOne() and fnTwo() through the fnBase():

    1
    2
    fnBase(fnOne, ["fnOne"]);
    fnBase(fnTwo, [1, "fnTwo"]);

    It would be possible to place metaData as a first argument in fnOne() and fnTwo() signatures but that would require additional args position handling in fnBase() so it is probably best to put metaData as the last argument.

    That’s it, hope it helps. Enjoy! :)

Back to top