【问题标题】:Where to implement a window.resize function in jquery-boilerplate?在 jquery-boilerplate 中哪里实现 window.resize 函数?
【发布时间】:2016-02-24 23:46:02
【问题描述】:

我正在尝试将使用 jquery 插件模式编写的插件之一转换为 jquery-boilerplate 提供的插件。我的插件依赖 $( window ).resize() 函数来使其具有响应性,但是当我尝试在 jquery-boilerplate 上使用它时,当我调整窗口浏览器大小时,Web 控制台会返回 TypeError:

function Plugin ( element, options ) {
    this.element = element;
    this.cfg = $.extend( true, defaults, options );
    this._defauls = defaults;
    this._name = pluginName;
    this.init();
}

// Avoid Plugin.prototype conflicts
$.extend( Plugin.prototype, {
    init: function() {
        this.windowWidth();

        $(window).resize(function(){
            this.windowWidth();
        });
    },

    windowWidth: function() {
        var w = $( window ).width();

        console.log(w);
    }
} );

Web 控制台返回: TypeError: this.windowWidth is not a function.

我也试过这种方式:

function Plugin ( element, options ) {
    this.element = element;
    this.cfg = $.extend( true, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();

    $(window).resize(function(){
        this.init();
    });
}

// Avoid Plugin.prototype conflicts
$.extend( Plugin.prototype, {
    init: function() {
        this.windowWidth();
    },

    windowWidth: function() {
        var w = $( window ).width();

        console.log(w);
    }
} );

Web 控制台返回: TypeError: this.init is not a function.

根据jquery-boilerplate,必须听jquery resize方法的代码要放在哪里?

我基本上是这样让它工作的:

function Plugin ( element, options ) {
    var element = $( element ),
        cfg = $.extend( true, defaults, options ),

        windowWidth = function() {
            return $( window ).width();
        };

    console.log( windowWidth() );

    $(window).resize(function(){
        console.log( windowWidth() );
    });
}

但这不是 jquery-boilerplate 团队的目的,那么在使用 jquery-boilerplate 插件模式时如何做到这一点?

【问题讨论】:

    标签: javascript jquery plugins jquery-plugins jquery-boilerplate


    【解决方案1】:

    此错误与 jquery-boilerplate 无关。 在编写任何插件之前,您绝对应该了解更多关于 Javascript 中的“this”关键字的信息。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2021-04-29
      • 1970-01-01
      相关资源
      最近更新 更多