Chain .ready and .resize into function?

点点圈 提交于 2020-01-06 23:41:12

问题


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:


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


来源:https://stackoverflow.com/questions/7372852/chain-ready-and-resize-into-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!