jQuery集合、功能和组织
jQuery collections, function and organisation
我有以下代码,它可以获取单个图像并对其应用特定宽度:
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();
}):
这很好,但感觉没有条理,感觉很草率。
最后,我希望得到以下方面的指导。
理想情况下,我希望它位于名称空间
Theme
下。我希望这种方法在Theme.Images
下使用模块模式。这可能吗?如果在名称空间
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();
});
};
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- 添加文字和评论功能更新Div
- JavaScript打印功能使日历停止工作
- Meteor-将选定窗体中的对象添加到集合中
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 如何防止网页加载后自动启动功能
- 除修剪外的其他功能
- 主干集合重置和解析
- 悬停功能触发器
- 使用数据上的角度更改设置集合的第一个元素的动画
- 为集合分配大量的模型弹药
- 如何使用backbone.js从集合中获取模型名称
- 使用angularjs向浏览器发送servlet响应(下载功能)
- Lodash从集合创建集合
- 删除CKEditor工具栏按钮,但不删除功能
- 异步facebook功能
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- jQuery滚动功能只工作一次
- 如何将中的两个geoJSON功能集合添加到两个层组中
- jQuery集合、功能和组织