我目前正在使用 JQuery Boilerplate 编写一个插件。但是,我在调用未在 init() 函数中调用的函数时遇到问题。样板注释指出可以通过 init 函数内的 this.functionname() 调用函数,但我不确定如果从其他地方调用它们如何执行此操作。
从这里查看其他问题,我似乎可以使用 JQuery Proxy 来实现此目的,但看不到如何将其应用于样板的示例。 有人可以告诉我,例如如何从 onEnterMobile 中调用 this.createCarousel() 或 this.settings 吗:
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = "dcResponsiveCarousel",
defaults = {
itemsPerPageOnMobile: 1,
itemsPerPageOnTablet: 2,
itemsPerPageOnDesktop: 3
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
$element = $(element);
this.settings = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
enquire
.register("screen and (max-width:767px)", this.onEnterMobile)
.register("screen and (min-width:768px) and (max-width:991px)", this.onEnterTablet)
.register("screen and (min-width:992px)", this.onEnterDesktop)
},
onEnterMobile: function (){
var deviceType = "mobile";
console.log(deviceType);
//this.createCarousel($element, itemsPerPage, deviceType);
}
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
最佳答案
好的,在就这个问题寻求一些离线帮助后,我想我应该发布一个如何在 JQuery Boilerplate 中使用 JQuery Proxy 的示例:
init: function() {
var that = this;
enquire
.register("screen and (max-width:767px)", $.proxy(this.onEnterMobile,this))
.register("screen and (min-width:768px) and (max-width:991px)", $.proxy(this.onEnterTablet,this))
.register("screen and (min-width:992px)", $.proxy(this.onEnterDesktop,this))
},
因此,我不只是调用回调函数 this.onEnterMobile,而是从另一个“代理”函数中调用该函数,然后该函数允许我传递“this”关键字的值。这允许我使用 this.settings 从插件中的任何函数访问我的设置,或使用 this.functionName 调用任何其他函数
关于javascript - 如何将 JQuery 代理与 JQuery 样板结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20959253/