0

目に見えないコンテンツをDOMにロードして、divのサイズを正しく計算できるようにするキャッシュ関数を作成しています(画像を含む)。キャッシュが完了したら、jQuery の遅延オブジェクトを使用して関数を実行しています。

私が抱えている問題は、キャッシング機能が完了すると、小道具オブジェクトを返す方法がわからないことです。下部にあるのreturn propsは明らかにプロパティ オブジェクトを返したい場所ですが、return が呼び出されるまでに _obj 関数が完了していないため、undefined が返されます。

下部にある私の完全な関数は props オブジェクト ( cacheHeight 変数を含む) を正しくログに記録していますが、遅延関数から 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;

    }
4

2 に答える 2