Tag Archives: Javascript

Recap my online year 2012

The year 2012 was for me a year that went way to fast. In the year 2012 I learned a lot new stuff, wrote several blog posts and read lots of blog posts and articles. First of all I want you to give a list of all blog posts I wrote this year. You can find the complete list here http://marcofranssen.nl/2012/ and here http://marcofranssen.nl/2012/page/2/.

JavaScript:

Windows 8:
Windows Phone:
Powershell
I even wrote a non-technical article:

Second I want to share my starred articles from my reading archive. I used pocket to bookmark, read and archive my articles, which enables me now to share all starred articles with you. Continue reading

Knockout JS mappings

Knockout JS is a JavaScript library for creating MVVM JavaScript libraries. In a previous post I already showed some of the cool features of Knockout.

http://marcofranssen.nl/2011/09/13/knockout-that-cascading-dropdown/

If you want to spike your knowledge on Knockout a little more first, please visit Knockout’s documentation.

In this article I want to zoom in on the Knockout mapping plugin. The Knockout mapping plugin enables you to easy map your JSON object into an observable JavaScript object. So here is a short example of what you’ll be able to do with it. So when you do an ajax request and receive a JSON result you can for example do the following.

Continue reading

Writing modular JavaScript without polluting the global namespace

Most of you have already seen a lot of spaghetti JavaScript code. One of the reasons you are reading this article will probably be, you don’t want to make the same mistakes as others have done. So let’s make the next step and stop polluting the global JavaScript namespace.

Why is it bad to have all your script code available at global level?

First of all you can possibly get a lot of errors when using modules developed by others, because you used the same names for you variables etc.

The second reason is, this code can’t be minified as good as the code I will show you later.

The third reason is, you are not forcing yourself well enough to write some clean JavaScript.

If you think I’m talking bullshit, you can better stop reading this article and continue giving JavaScript a bad name and scare of other developers with spaghetti code.

First of all we need to learn to write a JavaScript module. There are a lot of examples how to achieve this. This article is a in-depth description of the module pattern. Another well know example is the object literal pattern.

In my example I will use a pattern like in the first article because it will allow me to control visibility.

As you can see I use a very bare example, which is just enough to show you my point. We see we put all our JavaScript modules into a seperate file, which is really helpful when you need to maintain them. In the shoppingCart I gave you an example how to control visibility. The ‘updatePriceTotal’ function will be private within the module.

This way of writing your code looks pretty much like writing your code in c# or Java, isn’t it (except from the syntax).

But we are still polluting the global namespace. Now there are only two variables, but think of it when you complete the code I started. How many modules would be added? How much more you will be polluting the global namespace?

When opening the developer tools in for example Chrome and hitting F12 and navigating to the console tab and you type ‘product’ or ‘shoppingCart’ and hit the enter key you can access the objects from the global namespace.

So how can we wrap these modules in our own namespace?

As you can see we build a little wrapper around our modules. This wrapper is a self executing function which provides access to the elements from the global namespace. When calling this anonymous self executing function we provide our own namespace which we register at global level. We also provide window, document and undefined, because this gives advantages in performance and minification of your scripts. When you never use them in your script you don’t need to add them, but as a best practice I always add them so I will never forget them. Please note that the last parameter isn’t provided, so it is undefined.

Another best practice is to start each script with a semicolon, so you don’t have to bother about missing semicolons in other scripts. By starting with one at least this script file will not give errors on behalf of missing semicolons in other files. Issues most of the time occur when minifying your scripts.

Last but not least we have to register our module in our namespace. What we do is checking if the module already exists or else replace it with your module definition.

You may be asking, what if I want to use jQuery or whatever other script? Just add it to the wrapper so you can use it in you module.

Now we have achieved ‘product’ and ‘shoppingCart’ are not polluting the global namespace anymore. As you may already have noticed I used an _ in my namespace just to give a little bit more insurance it isn’t used by another external JavaScript. You can test this by opening the developer tools in for example Chrome and hitting F12. Try it out by typing   ‘_jsShop’ and hitting ‘enter’, you should see everything registered in the _jsShop namespace. Google Analytics for example uses the same naming conventions. They’re using the ‘_gac’ variable to provide you access to their api.

If you want to read more about JavaScript namespacing you should read this article. In this example I used one of the preferred patterns of Addy Osmani.

By writing your JavaScript like I described above, it will be very easy to use require.js to load your JavaScript dependencies asynchronously. For now see Addy Osmani’s article about AMD (Asynchronous Module Definition) to make the next step, until I finished my own, step by step article, which will proceed where I stopped in this article.

Also have a look at my jQuery events contributes to clean Javascript article, for a deeper dive into JavaScript modules working with events and jQuery. Note I didn’t use proper name-spacing here, but you know how to add it now.

Hope you enjoyed this article and we can build together on better JavaScript code. Share it with your friends and colleagues and give me some feedback so I can learn from you.

As a last advice…

Subscribe to Addy Osmani’s RSS Feed.

Auto retry concurrent commands with ncqrs

In a previous post I showed you some pseudo code Gregory Young mentioned in his DDD CQRS course I attended in Krakow, Poland. In this course Greg made clear to us locking of databases isn’t necessary. He showed us some pseudo code how to easily write a merge handler to handle all concurrency conflicts.

In my current project, based on the ncqrs-framework I implemented a simpler version of this merge handler which only retries each command if a ConcurrencyException occurs. To achieve this you can easily build a wrapper around the ncqrs commandservice.

You can choose to implement this in a WCF service or whatever you want. Every command that fails will be retried until it succeeds. I have tested this with hundred async JavaScript calls which send a real simple command (PrintLabelCommand). My domain only processes a LabelPrintedEvent. When sending these calls to the server my log tells me there are only 8 retries average. This is acceptable in our situation. If you have more complex scenario’s you will probably need a more advanced setup like the pseudocode in this blogpost shows you.

I’m still searching for a better name for my class, because SafeCommandExecutor isn’t the best name I think. So let me know if you have a better one. I hope this article will be useful for you guys. As always, please share…

If you improved my code let me know, so I can learn from it.

jQuery events contributes to clean Javascript

As the title reveals, this blogpost is about some clean javascript code example. Many developers dislike javascript because of different reasons. I think javascript is a pretty cool language. To prevent developers from disliking it and encourage them to show how great javascript can be, we all as developers have to write javascript in a clean way. This way lesser developers will be discouraged to use it.

In this blogpost I will show you how to write some OOP style javascript, which you know as of languages like c#. I will use jQuery to get to some clean javascript code. First of all I explain what I try to achieve with this code. I want to make two modules, one is a jQuery dialog which contains a form to post some products, the other one is some grid which shows the products. For this second one you could use for example jqGrid. I want these two modules to operate completely seperate from each other. They should be able to communicate with each other. Therefore I will use the jQuery event mechanism.

So first of all I will create my javascript productDialog module.

Second I need to init my products overview.

In order to let them communicate with each other on a specific page I implement some mediator, who will link some logic together for a specific page. At first glance this looks like overkill, and I see you thinking why not ding this in the page itself. Well when your modules have more events and more logic to link to each other this can grow into larger code. When the amount of modules on a page grows, you want a central place where you link all logic together. You can implement more mediators in case this keeps your code cleaner.

Last but not least you have to add these scripts to your page.

Conclusion

This code doesn’t look discouraging at all and I hope it didn’t do for you. The modules I showed you of here can be used seperately from each other except for the mediator. You can combine them easy with some mvc3 partials, which include the html for example. You can control which methods are public visible in the return value. I hope I lowered the threshold to write some javascript apps yourself. Maybe you’re writing very soon some cool Windows 8 javascript apps.

As always, share this post if you liked it! If you didn’t also share it :D .

Knockout that cascading dropdown

In this article I will explain how you can make cascading dropdowns with Knockout. Knockout is a javascript library which provides you some stuff to implement the MVVM pattern.  Knockout provides you the following stuff:

  • Declarative bindings: (Easily associate DOM elements with model data using a concise, readable syntax);
  • Automatic UI Refresh: (When your data model’s state changes, your UI updates automatically)
  • Dependency tracking: (Implicitly set up chains of relationships between model data, to transform and combine it)
  • Templating: (Quickly generate sophisticated, nested UIs as a function of your model data)

In the example below I use jQuery to get some json server data.

The Json server data should be an array of objects containing a ‘value’ and ‘text’ property. As you can see I use the ‘html5′ ‘data-bind attribute’ to map my view model to my UI elements.

For example your ASP.NET MVC3 action could look like this.

I wrote the examples in notepad, so there could be some issues. However if I did my job well this should be all to let all the magic happen.

Didn’t this knocked out a bunch of javascript code you would write normally?

If you like it share it! If you don’t share it!