OOP With JQuery Objects: Changing Prototype Of JQuery Arrays Vs. Creating My Own Objects Tree
Solution 1:
I think your inheritance model is backwards. It sounds like you want "Item" to be the "leaf" subclass, but you say "ParentItem inherits from Item". Item should actually inherit from ParentItem and so on.
In terms of OO design, it really depends how the arrays "in the background" will be used. Are these unique lists for each class instance? Are they static lists who are actually shared amongst all your class instances or among just one type of class instances? If it's the former, having an internal member variable to store these arrays for each instance makes sense. If it's the latter, you're really talking about, in classical OO terms, static member variables. That can be achieved by attaching the static member to the Constructor object as a normal attribute (and accessed as such), instead of on the prototype or assigned to "this" in the constructor. An example:
function A(name) {
this.name = name;
}
A.prototype.doStuff = function() {
A.staticList.push(this.name);
};
A.staticList = [];
var x = new A('foo');
var y = new A('bar');
x.doStuff();
y.doStuff();
A.staticList; // contains ['foo', 'bar']
Solution 2:
and all the "real" menu items (links pointing to some place in the website) are of type
Item
.
I would consider using a RealItem
or LinkItem
class for them that inherits from Item
as well.
Is it reasonable to create my own object tree, while having a lot of jQuery arrays in the background and keeping them in my objects' variables?
Yes. That what most apps with MVC model do - the view component controls the DOM, and keeps references to it (or jQuery wrappers) as properties/variables in the class.
Is there a cleaner (publicly more accepted) way of doing this? Maybe working directly on the prototypes of the jQuery arrays would be more reasonable?
I don't think that would be much cleaner.
How could this be done though?
Yes, you can inherit from jQuery collections, but I wouldn't recommend it.
Any other comment about my JS coding style?
The code could get a bit more DRY if you'd use some functional programming practises, but I think it is fine.
Post a Comment for "OOP With JQuery Objects: Changing Prototype Of JQuery Arrays Vs. Creating My Own Objects Tree"