我正在构建一个插件,并且为了打开/关闭某些行为,我正在使用 matchMedia 函数。但是在回调函数中,我需要传递一个参数来保留对此的正确引用。但是,当我尝试将参数传递给我的回调函数时,它说我的整个 addListener 回调函数是未定义的。当我尝试将它绑定到回调函数时,这同样适用。
TypeError: this.mediaQueryCheck(...) is undefined
关于addListener,我肯定缺少一些非常明显的东西,所以现在我只包含我的代码的一个非功能示例:
MyPlugin.prototype = {
version : '0.0.1',
mediaQuery : window.matchMedia(defaults.breakpoint),
mediaQueryCheck : function(mql){
if(mql.matches === true){ // if our mediaQuery matches
this.evalScrollPosition();
if(this.isLaunched === false){
// attach scroll handlers
$(window).on('scroll resize', this.evalScrollPosition.bind(this));
this.isLaunched = true;
}
}
else if(mql.matches === false){ // if the mediaQuery isn't active atm
if(this.isLaunched === true){
// remove handlers
$(window).off('scroll resize', this.evalScrollPosition.bind(this));
this.isLaunched = false;
}
this.fixedStatus = '';
this.unstyleContainer(); // remove positioning set by plugin
this.unstyleColumns(); // remove positioning set by plugin
}
},
init: function(){
// merge user options with defaults
this.config = $.extend({}, defaults, this.options, this.metadata);
// define mql object
this.mediaQuery = window.matchMedia(this.config.breakpoint);
var thatMediaQuery = this.mediaQuery;
// add listener to conditionally toggle scroll and resize listeners and bind this to not lose reference to this when running the mediaQueryCheck function
this.mediaQuery.addListener( this.mediaQueryCheck(thatMediaQuery).bind(this) );
// check mediaQuery to determine whether to apply eventListeners
// and run for a first time
this.mediaQueryCheck(thatMediaQuery);
return this;
},
/* .. rest omitted for brevity */
}
因此,我还尝试通过向该函数添加第二个参数然后将其传递给该函数,从而将对此的引用传递给我的 mediaQueryCheck 函数:
mediaQueryCheck : function(mql, context){
// '..'
},
init: function(){
// 'rest omitted for brevity'
this.mediaQuery.addListener( this.mediaQueryCheck(thatMediaQuery, this) );
},
但无济于事..有什么想法吗?提前致谢!