Tag Archives: Javascript

Passing Objects without Reference

30 Apr 2015

Here’s a little thing that I do to prevent passing object references when I really just want a copy of the object itself (a deep copy). This is super simple – much simpler than enumerating an object in order to reveal/copy its properties and values into a new object.

Here is an example of a closure that has a private variable called _data. There is a getter function called getData() that is meant to return the value of _data.

;(function(ns){

    var _data = {title:'test data'};
    
    ns.getData = function(){
        return _data;
    }

})(this.test = this.test || {});

Pasting the above in Chrome’s console you can see what happens when I create the variable dog to receive _data. I attempt to change the value of dog.title and see that it changes but when I view _data via the getter function I find that _data has changed even though it is encapsulated within the “test” namespace.

obj_by_ref_01

JavaScript passes objects around by reference, not by value, so what happened above is not a surprise. In layman’s terms dog maintains a reference back to the object _data which means that dog.title is in reality _data.title. Therefore modifying one is really modifying the other. Our intent is to pass the object as if it were a value without any reference back to where it came from.

What I need then is a way to break the reference chain so that I can receive the desired object as a “value” (kind of) instead of as a reference. I do that by stringifying the object into JSON and then parsing the JSON back into an object. As soon as the object is translated into JSON the reference no longer exists. Converting it back to an object via JSON.parse() gives me the desired “reference-free” deep copy of _data.

Here’s the same code with the JSON methods added:

;(function(ns){

    var _data = {title:'test data'};
    
    ns.getData = function(){
        return JSON.parse(JSON.stringify(_data));
    }

})(this.test = this.test || {});

And doing the exact same thing in Chrome’s console reveals that _data is untouched whenever dog.title is changed.

obj_by_ref_02

jqPlot Memory Leak

20 Nov 2013

Today I was brought into a conversation with our iOS developer about a portion of a client’s app that utilizes a charting component done in jQuery that is displayed via a web view. TestFlight showed the app crashing during prolonged use of the charting application. The first thing I thought was that memory wasn’t being released so I told the team I would look into it.

I ran the charting app in Chrome and watched the memory usage via the developer tool’s timeline. Sure enough, the familiar memory leak pattern became visible:

jqc_mem_leak_01

Using the tools Chrome provides to isolate a portion of the timeline and investigate what is happening revealed a theme of a “chart()” function being called. I tracked down where that was happening – and in the process discovered that jqPlot was in use (I had no previous experience with the app). I typed in a return statement at a stratgic spot to prevent charting from happening and then proceeded to once again torture the app and review the timeline. As you can see, the memory leak was gone:

jqc_mem_leak_02

No leak – the charting functions are the culprit – a quick search online revealed other people having the issue and one individual mentioning that jqChart has a “destroy” method that releases memory. Perfect, lets review our code again… and yes, all that is happening is that the previous developer is emptying the div wrapper of the chart data before filling it with a new one. That’s not releasing memory.

Here is the code before my edit:

$('#the_chart').html('');
var plot1 = $.jqplot ('the_chart', [fcccPoints, brandXPoints, crossoverPoint],
...

The div wrapper is unceremoniously emptied and the call to jqplot is assigned to a local variable. I needed to keep the reference to the chart so that I can destroy it properly so I moved the variable declaration outside of the function’s scope. I then changed the code to the following:

if (plot1){
    plot1.destroy();
    console.log('plot destroyed');
}
			
$('#the_chart').html('');
plot1 = $.jqplot ('the_chart', [fcccPoints, brandXPoints, crossoverPoint],
...

With those two tiny edits I again torture-tested the app and observed the timeline. As you can see jqPlot’s destroy method was doing its job and memory was now being reclaimed.

jqc_mem_leak_03

Regular Expression Method Fails on UA Strings

06 Jun 2013

This caught me at first – but upon closer inspection it makes sense – I was writing something that was looking at the User Agent of a device to see if it was Android using the “test” regex method and got the opposite result from what I was expecting. I expected that the “test” regex on the UA for the word “Android” would return true but instead I always got false. Here’s an example:

...
var isAnd = /Android/gi;
console.log(isAnd.test(navigator.userAgent));
...

On the surface this should be true, yet it returns false in the console. See this next example:

...
var isAnd = /Android/gi;
console.log(isAnd.test('android'));
...

Now the above returns true – something in the UA string is breaking the test. Here are the UA’s that I’ve tried with the above:

  • Galaxy Tab 2: Mozilla/5.0 (Linux; U; Android 4.1.1;en-us; GT-P5113 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
  • Nexus 7: Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19

On a whim I remove the forward slashes and perform the following test:

...
var isAnd = /Android/gi;
console.log(isAnd.test('Mozilla5.0 (Linux; Android 4.1.1; Nexus 7 BuildJRO03D) AppleWebKit535.19 (KHTML, like Gecko) Chrome18.0.1025.166  Safari535.19'));
...

Ah, this is what we’re looking for, that test works. So in order to do a successful pattern match using the “test” regular expression method on the User Agent string you would have to first remove all instances of “/” or escape them with a backslash (\/).

In Regular Expressions certain characters have a special meaning – I would think that a string that the regex is being run on would be immune but that’s apparently not the case. Forward slashes are used to create regular expression literals and if present within the string, well…. who knows what happens, presumeably its interpreted as another regular expression – and then things just won’t work. For that reason forward slashes need to be escaped with another character that has a special meaning in regular expressions – the backslash. So, this “\/” actually represents a single literal forward slash.

Yeah, this gets a little messy, you could do one of two things. You could clean the UA string first by using something like this (which, btw, is a little aggressive but is a good example of what you can do):

...
var str = 'some big string that needs to be "cleaned"';
str.replace(/([\[\]\*\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, "\\$1");
...

Or, and I like this approach a lot for this particular application, you could just use a different method entirely, such as the “search” regex method, which is impervious to this situation:

...
var ua = navigator.userAgent.toLowerCase();
console.log(ua.search('android') != -1)
...

And this gives us the predictable “true” as a result.

iScroll 4 Hacks

29 Nov 2012

Here are some hacks that I’ve discovered to get the most out of iScroll. The basic customization parameters are documented at www.cubiq.org’s website but you have to look at the cleanly laid out source to find the gems.

The current list of tips:

  • Improved Lock Direction
  • Faster Snap
  • Snap to a new element and only that element
  • Controlling Scroll Bar Position
  • Enabling SELECT, INPUT and TEXTAREA focus
  • Enabling hidden iScroll divs (where the wrapper div has display:none)
  • The bounce of death – non-scrolling content
  • Disappearing Lists
  • iScroll scrolls up when a scrolled element is clicked

Improved Lock Direction

There will come a time when you have two iScrolls on a page – one vertical and one horizontal. You will find that even if you enable “lockDirection” that iScroll will still be touchy. Try to scroll up and the slightest movement left or right will be caught by the horizontal iScroll. Try to swipe left or right and the slightest up or down movement will be caught by the vertical iScroll. Lock direction provides some improvement so be sure to enable it:

...
var myScroll = myScroll = new iScroll('yourWrapper', {lockDirection:true });
..

But to get even better “lockDirection performance” try the following hacks. Locate lines 470 and 473 within iscroll.js. We’ll want to change a number from 5 to 0.

Line 470 before:

...
if (that.absDistX > that.absDistY - 5) {
...

And line 470 after:

...
if (that.absDistX > that.absDistY - 0) { // yes, you can just remove the math too
...

Do the same with line 473. You should now notice that lockDirection with overlapping iScrolls works better than before.

Faster Snap

To enjoy faster element snapping open iscroll.js and scroll to line 437 where you will find this:

...
that.lastScale = scale / this.scale;
..

Subtract 10 from the lastScale value as seen below:

...
that.lastScale = scale / this.scale - 10;
..

Next, go to line 780 and find this line:

...
var deceleration = 0.0006,
...

Change the deceleration value to 0.002 per the next example:

...
var deceleration = 0.002, // 0.0006
...

Done, your snapping should be much “snappier”.

Snap to a new element and only that element

This tip is pretty cool – and simple. You can prevent “over swiping” in a snap-enabled iScroll by disabling momentum in one of two ways. The first approach is the easiest and most simple – and that is to disable momentum when you initialize iScroll, for example:

...
var myScroll = myScroll = new iScroll('introSliderWrapper', {snapThreshold:.5, momentum:false });
..

Note the “momentum:false” in the above configuration object. Momentum will be turned off.

Ok, so this next way of doing it is a **complete** hack and is really only of geeky interest – but if you look at the iScroll source you will see that there is some old code present that is very similar to the code that precedes it.

The new and old “duplicate” blocks are at lines 589 (new, momentum) and 608 (old, no momentum). Each block of code is surrounded by “if” statements that contain the exact same conditional. The “return” statement at the end of the first “if” block prevents the second “if” from running. It is necessary to comment the entire “if” block that starts at line 590 all the way to and including the return statement at line 605. Be aware that if you do this you are in effect creating a “global” change that will impact all iScrolls that you may employ. As a result, its best to stick with the perfectly functional momentum:false flag.

Anyway, to continue, locate the following code at line 589:

...
    // Do we need to snap?
    if (that.options.snap) {
      distX = newPosX - that.absStartX;
      distY = newPosY - that.absStartY;
      if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
      else {
            snap = that._snap(newPosX, newPosY);
            newPosX = snap.x;
            newPosY = snap.y;
            newDuration = m.max(snap.time, newDuration);
      }
    }

    that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);

    if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
    return;
  }
...

And with it commented out:

...
    // Do we need to snap?
    /*if (that.options.snap) {
      distX = newPosX - that.absStartX;
      distY = newPosY - that.absStartY;
      if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
      else {
            snap = that._snap(newPosX, newPosY);
            newPosX = snap.x;
            newPosY = snap.y;
            newDuration = m.max(snap.time, newDuration);
      }
    }

    that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);

    if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
    return; */
  }
...

Done.... when swiping you will no longer swipe past the the adjacent snap-to element. As mentioned, this is done easier by adding the momentum attribute to the iScroll configuration object.

Controlling Scroll Bar Position

Enabling scrollbars in iScroll is easy - making sure they are positioned where you want - easy as well as long as you position your div's appropriately. Even if you run into problems, you can hack the scroll bar into position.

To make scrollbars appear just pass a properly formatted configuration object to the iScroll, like so:

...
new iScroll('scrollWrapper',{
   vScrollbar: true, // the vertical scroll bar has been enabled
   momentum:true
});
...

This will make the vertical scrollbar appear - but in some cases the scrollbar may not be aligned with your scrolling content but aligned along the right-edge of the window. Sure, it may work but if you have a multi-column layout then chances are that you may not want the scroll bar "removed" from the scrolling area. The fix here is simple and achieved via CSS - make sure that your "scrollWrapper" div has its position style set to one of the following:

  1. absolute
  2. relative
  3. fixed
  4. inherit (as long as the inherited value is one of the preceeding three values)

Once the above is done then iScroll will properly place the scrollbar along side your content.

What if you can't change your css or don't want to? Then you can attack it with a little jQuery.

iScroll will place the scrollbar divs within the scroll wrapper but without an id. Since the wrapper does have an id we can use jQuery to get the wrapper's children of which the scrollbar is a member. The last child will always be the scroll bar. For example:

...
window.addEventListener('load',function(){
   new iScroll('scrollWrapper',{ // the scrollbar will be the last child within the wrapper
      vScrollbar: true,
      momentum:true
   });

   // lets get the wrapper's children
   var children = $('#scrollWrapper').children();
   // the children array has a length of two, the last one is always the scrollbar
   // position the scroll bar as desired
   children[1].style.height = 350 + 'px';
   children[1].style.top = 0 + 'px';
   children[1].style.left = 190 + 'px';
},false);
...

As you can see from the above its a simple matter to attack the iScroll scroll bar. If you like you could obviously change this:

children[1].style.height = 350 + 'px';

To this:

children[children.length-1].style.height = 350 + 'px';

So that you **always** get the last child as who knows how you're structuring your content.

In addition to this you may not always have a scroll bar present depending on the length of your content. Therefore, we have to check for its existence in some way. In a typical setup the wrapper will only have a single child if the scrollbar is not there. The following check is based on this assumption:

...
window.addEventListener('load',function(){
   new iScroll('scrollWrapper',{ // the scrollbar will be the last child within the wrapper
      vScrollbar: true,
      momentum:true
   });

   // lets get the wrapper's children
   var children = $('#scrollWrapper').children();
   if (children.length > 1){ // if there is more than one child, the scrollbar must be present
      children[1].style.height = 350 + 'px';
      children[1].style.top = 0 + 'px';
      children[1].style.left = 190 + 'px';
   }
},false);
...

Enabling SELECT, INPUT and TEXTAREA focus

iScroll will disable the ability to give focus to certain form elements preferring instead to treat all interactions with the screen as something that must go through iScroll itself. You can get around this by adding the following function to the onBeforeScrollStart event - shown here as a configuration object while instantiating iScroll. You could also just add it to the iScroll source - view source, scroll down until you see the onBeforeStartEvent and add the function there.

...
var scroll = new iScroll('content',
   {scrollbarClass: 'myScrollbar',
    handleClick: false,
    useTransform:true,
    onBeforeScrollStart: function (e) {
        var target = e.target;
        while (target.nodeType != 1) target = target.parentNode;
        if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
            e.preventDefault();
	}
    });
...

Enabling hidden iScroll divs

This isn't a hack per se as iScroll has a method to deal with the issue. In cases where you instantiate an iscroll on a hidden wrapper div and then reveal the wrapper by changing its display style to something other than "none" you will find that the iScroll-ed div will just bounce in its wrapper, refusing to scroll.

The fix is to do the following **after** you have revealed the wrapper - the example uses the refresh and scrollTo methods to enable scrolling:

...
// instantiate a new iScroll
var myScroll = new iScroll('myDiv');

function reveal_iScroll_div(){
   document.getElementById('myDiv').style.display = 'block';
   myScroll.refresh();
   myScroll.scrollTo(0,0,0);
}
...

...

The bounce of death - non-scrolling content

Sometimes your content will just bounce in its container and not scroll at all. There are a couple things that cause this - 1 of them is the section preceding this one, the other is likely to be a simple line of CSS. Make sure that the div that is wrapping your content has a css display value of "block".

Disappearing Lists

Sometimes you'll have an iScroll whose contents are updated according to whatever the user has selected. If you have a long list and quickly scroll through them - and then try to update the contents of the scroll wrapper while your list items are flying by you may find that the list may update with new content but not be visible. That is, if you inspect the DOM you plainly see that your elements are there correctly positioned but they do not display (observed in Android 4.1.2).

It appears that we may need to stop the scrolling before updating the list. Something like this:

...
if (_myScroll){
    _myScroll.scrollTo(0,0,0);
}
// now update the list
...
// _myScroll.refresh() might not work here, the "scrollTo" before the update seems to help
...

iScroll scrolls up when a scrolled element is clicked

(7/15/2016) I just had this particular issue that took me quite a while to figure out - I had inited an iScroll with content that appeared to function correctly, but no matter what buttons I clicked in my scrolled content the result was a) what I programmed the button to do, and b) the iScroll would scroll back to the top (interestingly the scroll bar would NOT scroll to the top).

Turned out that I had instantiated the iScroll twice in quick succession on the same variable - maybe creating some sort of race condition? You would think that one would overwrite the other... but fixing the code so that I created an iScroll instance only once resolved the issue.

Convert XML to JSON

27 Nov 2012

Having a library of scripts in your back pocket comes in handy – this one is a gem IMO, it is an XML to JSON converter written in JavaScript. I spent the better part of my day trying the wide variety of scripts that a simple Google search yielded. Some didn’t work, others did albeit with quirks (i.e., output that was “technically” JSON while having a less than desired structure).

After much searching and testing I’ve found one that is “perfect”; inserting null values where needed, arrays appearing where they should, extra objects weren’t inserted, etc, etc…. in addition the author shared his test scripts to show the robustness of his work. Download it from here:

http://michael.hinnerup.net

The library claims to also convert JSON to XML – I’ve not tried it but if the quality of the XML to JSON portion is any indication then I expect it should work just as well.

Update 1/2/2013

Michael appears to have updated his blog as all of the content has vanished – and so as a service to others (and myself) I’m providing a link to the js. Whenever Michael gets his blog backup I’ll revert to linking to him, in the meantime you can download the library here:

xml_to_json.js

Also, as his documentation has also disappeared I’ve added a quick example below showing how to request an XML resource via JQuery and turn it into JSON once its been received by the client:

...
function getXML(){
  $.ajax({
    url:      hostURL,
    type:     'GET',
    dataType: 'xml',
    error:function(xhr,status,err){
      // handle errors here
    },
    success:function(responseData,status,xhr){
      if (responseData.childNodes.length > 0){
        var obj = xmlJsonClass.xml2json(responseData); // xml to json conversion happens here
        console.log(obj);
      } else {
        console.log('Response did not appear to contain any children.');
      }
    }
  });
}
...

Tip

I had XML that contained CDATA sections – what the XML-to-JSON script did was create a needless object for the CDATA – a structure that looked like this:

...
{test:
   {test1:'something',
    test2:'something else',
    test3:{#cdata:'another something'}
    }
}
...

Note the value for “test3” – instead of putting the string “another something” as the value the library put in another object. To avoid that, open the xml_2_json.js file and go to line 186 and note the for loop:

...
for (n = xml.firstChild; n; n = n.nextSibling) {
   o["#cdata"] = this.escape(n.nodeValue);
 }
...

That block of code is where the extra object gets inserted – simply change it to this:

...
for (n = xml.firstChild; n; n = n.nextSibling) {
   //o["#cdata"] = this.escape(n.nodeValue); // << original line
   o = this.escape(n.nodeValue); // << new line
 }
...

And now the sample output above appears in a manner that makes more sense:

...
{test:
   {test1:'something',
    test2:'something else',
    test3:'another something'
    }
}
...

Logo

All content © 2012-2017.