从延迟嵌套函数返回值

时间:2013-08-07 14:48:12

标签: javascript jquery

我正在编写一个缓存函数,它将不可见内容加载到DOM中,以便可以正确计算div大小(包括图像)。我正在使用jQuery的延迟对象在缓存完成后运行一个函数。

我遇到的问题是,一旦缓存功能完成,我无法弄清楚如何返回 props 对象。底部的return props显然是我想要返回我的属性对象的地方,但它返回未定义,因为_obj函数在调用返回时尚未完成。

靠近底部的完整功能正确记录了props对象(包括 cacheHeight var),但我无法弄清楚如何从中返回props对象延期功能。我想做return _obj(content).done(complete);之类的事情,但显然会返回延迟对象,而不是完整函数的返回。

    cache : function(content) {

        // Vars
        var props;
        // Deferred switch
        var r = $.Deferred();

        /*
         * Cache object
         */
        var _obj = function(content) {
            cacheHeight = 0;
            cache = document.createElement("div");
            cache.style.visibility = "hidden";
            $(cache).css("position", "fixed"); // prevents parent's size being affected
            $(cache).append(content);
            $(contentWrapper).append(cache);
            children = $(cache).children();
            // Image loader
            var imgs = $(cache).find('img'),
                img_length = imgs.length,
                img_load_cntr = 0;
            if (img_length) { //if the $img_container contains new images.
                imgs.on('load', function() { //then we avoid the callback until images are loaded
                    img_load_cntr++;
                    if (img_load_cntr == img_length) {
                        remaining = children.length;
                        $.each(children, function(index, value) {
                            --remaining;
                            cacheHeight = cacheHeight + parseInt($(value).outerHeight(false));
                            if (remaining == 0) {
                                props = {
                                    height : cacheHeight
                                }
                                r.resolve();
                            }
                        });
                    }
                });
            }
            return r;
        };

        /*
         * Return cached object data
         */
        var complete = function () {
            console.log(props); // Correctly logs props object
        };

        // Resolve when finished
        _obj(content).done(complete);

        console.log(props); // Logs props as undefined (not good)
        // Return?!?!
        return props;

    }

2 个答案:

答案 0 :(得分:0)

如果将一个函数作为回调函数传入缓存参数来访问props变量,该怎么办?我想知道你是否在它被设置之前返回道具。

答案 1 :(得分:0)

调用resolve时它可以接受参数,所以你应该这样调用它:

r.resolve(args);

然后完成将自动将其转移到您的回调:

         /*
         * Return cached object data
         */
        var complete = function (args) {
            //use args as you see fit
            ready = true;
        };

有关详情:http://api.jquery.com/deferred.resolve/

相关问题