JQuery Collections, Features, and Organization

I have the following code that takes a single image and applies a specific width to it:

function Foo ( img ) { this.image = img; } Foo.prototype._getWidth = function( ) { return this.image.data('largest') + 'px'; }; Foo.prototype.applyWidth = function( ) { this.image.css( 'width', this._getWidth() ); }; var img = Foo( $('img') ); img.applyWidth(); 

However, I'm struggling to process a collection of jQuery images, for example $('img') without a for loop or $.each() inside each of the functions (I have more than the two functions shown above).

So far, the best I've come up with is:

 var temp = []; function Create ( imgs ) { $.each( imgs, function( i ){ temp[ i ] = new Foo ( $( this ) ); }); return temp; } Create( $('img') ); $.each( temp, function() { $(this).applyWidth(); }): 

It works great, but it doesn’t feel organized, it feels sloppy.

Finally, I would like to get some recommendations on the following.

  • I ideally want this in the Theme namespace. I need this method under Theme.Images using the module template. Is it possible?

  • If under the namespace Theme.Images one could make a call, for example Theme.Images.applyWidth() , which calls applyWidth() on all images in temp , bearing in mind that each img will have a unique value for _getWidth() . At the moment, I believe that I will need the Theme.Images.temp and call applyWidth() inside the loop.

I am really starting to appreciate the point of inheritance in javascript and would like to continue it.

+6
source share
2 answers
 var Theme = (function(){ function Theme(images) { var _this = this; this.images = []; images.each(function(){ _this.images.push(new Image(this)) }); } var Image = (function(){ function Image(imageDOM) { this.image = $(imageDOM); } Image.prototype._getWidth = function( ) { return this.image.data('largest') + 'px'; }; Image.prototype.applyWidth = function( ) { this.image.css( 'width', this._getWidth() ); }; return Image; })(); Theme.prototype.applyWidth = function(){ this.images.forEach(function(el){ el.applyWidth(); }); } return Theme; })(); 

So you can do:

 var MyTheme = new Theme($(some_selector)); MyTheme.applyWidth(); 
+1
source

I like that you are looking for a Collection class.

 function Images() { var that = this; that.foos = []; $('img').each(function() { that.foos.push(new Foo(this)); }); } Images.prototype.applyWidth = function() { $.each(this.foos, function() { this.applyWidth(); }); }; 
+1
source

Source: https://habr.com/ru/post/952294/


All Articles