Mixing OOP javascript with jQuery DOM manipulation

I want to start development with the development of javascript jQuery. I recently read “JavaScript: Good Details” by Douglas Crockford and am well prepared for prototype object-oriented development.

Now I'm trying to figure out how to weave the use of jQuery with the patterns presented by Crockford. I can think of two reasonable approaches:

  • Add methods for DOM objects returned by jQuery (possibly using the jQuery extension method)
  • Add the DOM objects returned by jQuery as properties of domain objects (and vice versa), and delegate calls accordingly. This allows you to use the prototype methods of domain objects.

What recommendations do you have for mixing javascript OOP with jQuery DOM manipulation?

+4
source share
1 answer

Your approaches are very interesting. I will give you my opinion

  • Add methods for DOM objects returned by jQuery (possibly using the jQuery extend method)

I think this is bad practice. What for? you added methods to individual objects, so these objects do not have a class (well, they can have one, but we do not define a class method). This will be an object practice, not an object-oriented practice.

  • Add DOM objects returned by jQuery as properties of domain objects (and vice versa) and delegate calls, respectively. It has the ability to add methods to the prototype domain objects.

I think this is a very, very good practice, and as you say, we will add methods to prototype objects instead of object instances. This is oop.

Just a comment because I think this is a very frecuent problem. When creating jquery plugins, I think it’s good practice to make a class for the plugin and add the corresponding instance of the class to the node where it was applied using .data (), so we do not lose the link to the example. This is all the more close to OO practice, I think it can be done for plugins.

Hope this helps. Best wishes

+2
source

All Articles