I'm trying to take an existing working code base and make it object oriented using JavaScript. My system takes JSON containing groups and items in a one-to-many relationship, and visualizes this on a page. The items can be moved into different groups, and their positioning within those groups also needs to be calculated. As such, events will need to be established which are aware of both the groups and tickets around them.
I'm using John Resig's simple JavaScript inheritence setup to establish two classes, Item
and Group
. When each Item
is instantiated it refers back to it's parent Group
. My issue arises when I want to establish my events, and is most easily explained by the following function:
var Group = Class.extend({
...
// Calculate where to place the new item within the group
calculate_new_position: function(item) {
var pos = -1;
// Loop through all DOM items in groups body
$(".item", this.elBody).each(function(i) {
// Retrieve it's class object
var next = $(this).data("_obj");
// Calculating things using the class reference
var lowerPrio = item.tData.priority < next.tData.priority,
lowerId = item.id < next.id;
if(lowerPrio || lowerId) {
pos = i;
return false;
}
});
return pos;
},
...
)};
Note the use of the .data("_obj")
in the above snippet. Essentially, when I need to do something like sorting the items, then I need to know the object (model) corresponding to every item's DOM (view/controller) in the group. Now, I could establish my Group
class so that when I create each Item
I add a reference to it from within my Group
(e.g. so Group.items = [i1, i2...]
), and then rather than iterating over the DOM elements, I could iterate over the Item
instances. However I think I'd run into similar problems down the line, such as when I want to move an Item
into a different Group
(as the Group
would not know about the Item
).
Long story short: is it intrinsically dangerous/naive/pointless to have a class which when instantiated creates a DOM element, which then in turn points back to the class? This feels like circular dependency, and some recursive nightmare, but perhaps a reference to an object isn't such a terrible thing. If I'm doing anything else really stupid, and there's a much simpler way, then please point that out as well.