Chain .ready and .resize into function?

2019-09-04 03:31发布

Inside this object, I have a property Response.action that is meant to be a shorthand for triggering code on jQuery's .ready and .resize simultaneously. The comment in the code block below demonstrates its usage. Response.action works on .ready but not on .resize. Can anyone see why and/or suggest how to make it work for both?

window.Response = (function($, window, undefined) {

    var Response = {},  // object
        $window = $(window),
        $document = $(document); // cache selectors 

    /*
    Response.action()
    This triggers code on .ready *and* .resize 
    usage:
                Response.action( myactions );
                function myactions() { 
                    // do stuff
                }       
    */  
    action = function( code ) { 

        var code = ( code !== undefined ) ? wrap() : false; // apply wrap() if we have code

        function wrap() {
            $document.ready(function() {
                $window.resize(function() {
                    code // input
                }).resize(); // trigger resize handlers
            }); // close .ready function
        }

        return code; // wrapped code fires on .ready and .resize
    },
    Response.action = action;

    return Response; // return object

})(jQuery, window); // expose to global object

This is for responsejs.com - the full lib (in progress) is there.

I'm using one of the other properties to test it. The .band property is solid on its own:

Response.action( myactions() );
function myactions() { 
        if ( Response.band(600) ) { $('header').html('600px or wider'); }
        else { $('header').html('below 600px');  }
}

Update: this works:

Response.action = function ( func ) { if ( typeof func !== 'function' ) { return false; }

$(function () {
    func();
    $window.resize( func );
}).resize();

return func;

};

with this usage syntax:

Response.action( myactions );
function myactions() { 
        // do stuff
}

*Note that in the call it needs to be myactions as opposed to myactions()

1条回答
Juvenile、少年°
2楼-- · 2019-09-04 04:29

How about

window.Response = (function ( $, window, undefined ) {

    var Response = {};

    Response.action = function ( func ) {
        if ( typeof func !== 'function' ) { return false; }

        $(function () {
            func();
            $( window ).resize( func );
        });

        return func;
    };

    return Response;

})( jQuery , window );
查看更多
登录 后发表回答