简体   繁体   中英

Where to implement a window.resize function in jquery-boilerplate?

I'm trying to convert one of my plugin written with the jquery plugin pattern with the one provided by jquery-boilerplate . My plugin relies on a $( window ).resize() function to make it responsive, however when I try to use it on the jquery-boilerplate the web console returns a TypeError when I resize the window browser:

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 console returns: TypeError: this.windowWidth is not a function .

I tried in this way too:

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

and the web console returns: TypeError: this.init is not a function .

Where do I have to put code that have to listen to the jquery resize method according to the jquery-boilerplate ?

I basically made it work in this way:

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

But this isn't the purpose of the jquery-boilerplate team, so how can I do this while using the jquery-boilerplate plugin pattern?

This error has nothing to do with jquery-boilerplate. You definitely should learn more about "this" keyword in Javascript before writing any plugins. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM