Archive for October, 2013|Monthly archive page
I thought I would share this gotcha in the hope it saves the rest of the world some time. Here’s the deal……
In IE8 and below when using substr() to parse a string you cannot use -1 as the startIndex parameter: it will return NaN and error out. As an example, this will not work:-
var index = id.substr(-1, 1);
Instead you would need to do the following:-
var index = id.substr(id.length-1, 1);
Very small Yay!
I have recently been wrestling with Backbone.js to get it to correctly parse nested collections. There are numerous ways you can do this including using the plugin Backbone Relational. However, if you just want to do it yourself without the plugin then this is the approach that I found worked for me….
I have a collection of models. Some of these models might contain a nested collection of the same models. In my JSON this is set up as an array. The issue I was getting was that it was remaining as an array and not getting parsed into the collection of models I wanted it to be. This was a problem because I was navigating through the data recursively and I wanted to be able to treat each model as a Backbone model and not just a plain old object.
My model class is called ShellMenuModel and my collection class is called ShellMenuCollection. The model attribute where the nested collection would live is called subMods. Here is the model code:-
The key to solving this problem was using the initialize function to manually parse the collection. In this function we check to see if the subMods collection attribute exists, if it does exist then you instantiate a new collection and in the constructor pass in the subMods array. The collection then gets parsed into a collection and set up as the subMods attribute on the parent model.