Fix for Issue 2147

As per #2147, fix for js error. Also preventing a memory leak.