Friday, September 20, 2013

knockout with jQuery Autocomplete


Today we are going to look at how to implement a jQuery autocomplete feature against a UI which is bound to a model via knockout bindings. And in this exercise you'd also learn about how to write your custom bindings using knockout's framework.

So in this exercise I am simply going to write a small app which is going to list some task and allow us to assign some user to the task. Here is the example below:

jQuery autocomplete with knockout.js
The important parts in the code are:

1. The data-bind declaration for the textbox

<input type="text" 
    data-bind="value: name, autoComplete: {label: name, value: id}"/>

2. The custom binding declaration

ko.bindingHandlers.autoComplete = {
  init:function(el, va, ba, vm, ctx){
    var prop = va();
    $(el).autocomplete({
      source: users,
      select: function(evt, ui){
        evt.preventDefault();
        var item = ui.item;
        console.log(item);        
        prop.label(item.label);
        prop.value(item.value);
      }    
    });      
  }
};

Knockout exposes a bindingHandler property via which we add a new property. That property can have any methods defined in it, but the following two are reserved for knockout – init & update.

The two functions have the same signature:


ko.bindingHandler.yourCustomHandler = {
    init: function(element, valueAccessor, bindingAccessor, viewModel, bindingContext){
        //logic
    }
};

init is called when a particular dom element is created in the context of binding. update is called whenever there are any changes in the model. To get more idea about the arguments these functions have, visit the knockout docs.

We've used only the init function since that is the only one required.

But what is the significance of the value binding there?

Without the value binding there wouldn't be a two-way binding per se.

The autocomplete part is pretty much self explanatory. This app is fairly simple. The autocomplete options don't take part in the model. However, if they did, that would have to be in a different blog post all together.

Can we do the same exercise without the value binding?!
+ me on Google Plus if you figure that out!... ;)

Friday, July 19, 2013

knockout.js

How this library sells itself?
  • Its not jQuery.  
  • It attaches to DOM level elements and all, however it doesn't provide a mechanism to traverse the DOM via selectors (like jQuery does) or via any other mechanism. 
So now the question comes...where then do you use it?

If you are a novice programmer, and you've just begin to like jQuery, chances are that you'd tend to build complex web pages without much concern on how to manage the huge amount of data your web page might be holding. There might be ajax callbacks which update the data, and subsequently you are writing code to add new DOM elements to the web page or update the existing DOM elements correspondingly.

However, when moving up from that novice state to a relatively more experienced state you'd begin to think if there is anything out there which would save you from updating DOM each time your data (or some part of it) updates or refreshes from the server...your experience might call out to you and say, no there’s got to be a better way to do this...enter knockout.js

Now this library is not a replacement for jQuery or any other library which serves to be a low-level DOM api. It is meant to complement it.

To really appreciate the power of knockout.js study the example below:

See the Pen ko example by arun.jayapal (@deostroll) on CodePen.


To simply add a new row to the table, I didn't have to write any DOM level api stuff like document.createElement, document.getElementById, or, go through the headache of appending it as a child of the students table element, etc.

Hope you've enjoyed the small example. Happy programming...

Hey!! Why not play around with the fiddle?! Try adding a delete functionality to this table and find out how easy that goes. You can paste a link to that fiddle in the comments below...

Sunday, July 29, 2012

dependency injection in python

Dependency injection (DI) is a software reuse pattern, and has quite a lot of literature associated with it. Most of the videos you see on this topic start off with a small explanation of the SOLID principles. These principles are a set of guides to good object-oriented (OO) design. The 'D' in SOLID refers to dependency inversion - or dependency injection.

I found a very good video which explains the situation where we would actually go for this pattern. It is targeted to php audiences, but those who understand the basic OO principles can follow it easily.

Now python being a dynamic language the term dependency injection isn't as popular as it is in c# or java. This being because, python is a dynamic language. You assume can link to any bit of code at runtime and execute that functionality. If you have spawned up an instance of the python interpreter, you can write functions on the fly and execute them.



Python also has the notions of modules: they are mechanisms to enforce some modular approach to programming. This is also a way to accomplish reuse. You can write some functionality in them and import them into your main script or the interpreter instance, and use that functionality right away. In fact a lot of what is in the python standard library is reused this way.


Below is an example showing you how you can write your own module and import that one:



I have my own implementation of dependency injection hosted on github right now. It is inspired from spring.net library (.net library for di). But before you look at the code, and, if you are still unsure of how exactly python import statements work, you should look here.

Looking forward to interact with people on my google plus profile. Happy programming.

Thursday, January 26, 2012

The loader pattern in JavaScript based applications

Most of the web applications you see are complex ajax driven applications. There is almost always an asynchronous call to a web service to get data; and having received that data we go forward with whatever our requirement. But consider a simple page such as this:
  This is a simple customer form which collects the customer personal details and credit card information. The form is useless. It needs vital data such as credit card types, titles, and, country values etc all available in the UI. But the catch here is we have to make api calls to the corresponding services to get it. But we'd have to wait to get the response from those three services.

This really stupid application is actually a mockup of what to expect in the real world. However, you may not agree. If your requirement ever runs on the same lines such as these, I assume you have the power to change the entire solution design. However, some ill-fated teams can't do anything to that regard. Hence we have something like this popup. But, please don't consider this rationale to be the reason behind the pattern.

Below we have kind of solved the problem of the above form becoming congruent for user input with a button click. This is just to demostrate the idea. I am using jQuery for my ajax calls, and jsFiddle apis to load some mock data. The point is I should not be able to do anything until the whole form is loaded. In practical implementations what happens on button click usually happens when the web page loads...



You can find the crux of the loader pattern in the loadForm function.

Saturday, December 10, 2011

Browser cookies can also be created this way...

While inspecting some public websites I came across an interesting server-side-cum-JavaScript way of creating cookies. Well this must be an old technique, but nevertheless I am quite new to it.

The server-side code is the easy part. Because I assume people would have done this at sometime in their software development lifetime. If not just take a look at the following codeproject article: Beginners guide to ASP.NET Cookies

The JavaScript side of how things are to be done, I saw a code something like this:

var img = new Image();
img.src = 'http://yourdomain.com/CreateCookie.aspx';

That's it. This particular code of javascript when executed will create the cookie, provided the url in the above example returns a response that set the browser cookie. The particular image object isn't even added to the DOM, but the cookie is created and associated with the page!

The main advantage is, you don't have to have the hassle of creating cookies via javascript; especially cookies which belong to other domains (different from your website). In those websites we were supporting the main rationale was reuse, and maintainability. So they added similar code in a separate js file and added it to the page manually. When they didn't want it they'd manually remove it and edit the page. They didn't have the need to make any change to server side code to add/remove those cookies.

Thursday, November 17, 2011

a javascript based menu system

I have been working on a javascript based drop down menu system. Its kind of like the menu system on your desktop word processor or browser. Functionality wise - its much more primitive than its desktop versions.

The original inspiration came from a web application which had the looks of a windows forms application - the same form surface, buttons, etc, and of course even the menus to a degree. It was being used at my client's end. It is a very old application; probably dated back to the time where DHTML was hip. The problem with it obviously was: it contained very obsolete markup. Those sort of markups only work on old versions of IE (< 5.0). And moreover, the damn thing wouldn't render on any other browser.

But I really liked the effort put into the development of the various web pages. It was developed by a different vendor; we had to maintain the application - as usual we had no idea who that vendor was, and what that vendor had done.


I am not going to really explain everything in detail. The code is simple, and the design is pretty straight forward. I am just embedding the example here:

Saturday, October 22, 2011

Managing your application settings in .net programs

Lets say you are writing code for your data layer. Ideally you'd be creating all the types this layer has to deal with, and most importantly, how these types get instantiated with data from your database. Hence there is always a connection string involved. But have you noticed where the connection string is stored?

For n-tier applications we mostly build the data layer as a dll (or a class library project), and finally add it to the presentation tier (just saying). However while you were doing development you would have used the dataset designer (or any similar designer) which allows you to manage your connection string for you. Our connection string, if you are using dataset designers, quietly becomes an application setting. But all of this is probably stored temporarily in your class project's app.config.

When the dll is added to another project, say a asp.net application, the dll will actually look for its configuration in the asp.net application's web.config. But its not there? One thing to note: simply adding the dll, VS doesn't copy its settings and merge it with the target application's config.

A strange fact to make note of again: the dll may not have its corresponding configuration. However this doesn't mean the application settings are completely absent. When we build the dll, the configuration at that instant, is actually written into the dll. Hence if we are trying to get the value of the connection string, we might get the string which belonged to the test db server. But anyhow, in production, we'd still want to change the setting value at some point or another.

This is quite possible in the target application config file again. In the sample solution I have shared below I have created a class library project which has an application setting. I have created a simple class which reads the application setting and returns this. I have directly outputted this value in ConsoleProjectA. You'll find that the display has the same string - this was the string we have set while making the class library project. In the 2nd console application project, the same code produces a different value. If you study the app.config of this project you'll understand how to change the application settings of the dll.

The zip file which has the sample solution which demonstrates this concept can be accessed here.