views:

77

answers:

2

My current style of programming is OO javascript using the Class.extend function by John Resig: http://ejohn.org/blog/simple-javascript-inheritance/

This has been fine but I find myself writing numerous setters and getters that only get used on init. Also, it seems to lead to memory leaks in IE when storing instances of these objects in an array for later use.

I am starting to favor smaller, cleaner, and more readable code over the seemingly overkill OO approach. My idea is to now just base everything off the dom using jquery and storing data properties using the .data method. For example, instead of creating an instance of a new Tweet object, you would simply add a div to the dom with class tweet and simply add the properties like author, timestamp, reply to, sent from, etc. in the .data cache for that dom element.

What do you think of this less structured approach when creating instances of things such as items in a stream like twitter? Is OO and prototypal inheritance the best approach or is strict dom manipulation better?

+1  A: 

My brain tells me that the very structured Javascript that doesn't rely on the DOM manipulation and calling in and out of it with jQuery would be ideal.

However, I just wrote an HTML5 web app that runs offline using the built in SQLlite and did it using primarily .data and storing information in divs and getting them out of there. It was simple, clean, and easy but for some reason didn't feel right.

But it worked well.

Ryan Doom
>> "but for some reason didn't feel right."But if it's clean, simple, fast, and efficient, why wouldn't it feel right? Because it's not best practice?
abadaba
Ryan Doom
+1  A: 

I am doing something similar. I took the OO javascript approach. But instead of using arrays i use a key value object. The key is a unique dom element id, the value is the object itself. it looks something like this.

for example:

var collection = {};
var $domEl = jQuery;              // jquery dom element
var myClass= new MyClass($domEl); // class instance

// add to collection
collection[$domEl.attr('id')] = myClass;

// remove
delete collection[$domEl.attr('id')];

Really it depends on the complexity of your objects. A strictly .data approach would need to rely on plugins for all of the related methods, and then store data in the elements data. I have many methods that are not related to strictly element interaction, so i keep the methods and data in the class.

Josiah Ruddell