jQuery集合、功能和组织

jQuery collections, function and organisation

本文关键字:功能 集合 jQuery      更新时间:2023-09-26

我有以下代码,它可以获取单个图像并对其应用特定宽度:

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();

然而,我正在努力处理jQuery图像集合,例如没有for循环的$('img')或每个函数中的$.each()(我有不止这两个函数)。

到目前为止,我想到的最好的是:

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

这很好,但感觉没有条理,感觉很草率。

最后,我希望得到以下方面的指导。

  1. 理想情况下,我希望它位于名称空间Theme下。我希望这种方法在Theme.Images下使用模块模式。这可能吗?

  2. 如果在名称空间Theme.Images下,是否可以进行诸如Theme.Images.applyWidth()的调用,该调用将在temp中的所有图像上调用applyWidth(),记住每个img将具有用于_getWidth()的唯一值。目前,我认为我需要循环Theme.Images.temp并在循环中调用applyWidth()

我真的开始欣赏javascript中的继承点,并希望继续使用它。

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;
})();

那么你可以做:

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

听起来你在寻找一个"Collection"类。

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();
    });
};