如何在jQuery中将两个匿名函数连接在一起

时间:2013-05-28 23:27:09

标签: jquery

如果可能的话,如何将两个匿名函数连接在一起,以便在另一个完成后运行?

我的尝试:

    $(function() { 
        $('body').addClass("loading"); 
        function preload(arrayOfImages) {
            $(arrayOfImages).each(function(){
                $('<img/>')[0].src = this;
            });
        }

    },
    $(function() { 
        $('body').removeClass("loading"); 
        }); );

功能:

    $(function() { 
        $('body').addClass("loading"); 
        function preload(arrayOfImages) {
            $(arrayOfImages).each(function(){
                $('<img/>')[0].src = this;
            });
        }

    });

    $(function() { 
        $('body').removeClass("loading"); 
        });

JCOLEBRANDS代码:

   function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $(this[0]).src = this[1];
    });
    $('body').removeClass("loading"); 
}
$(function() { 
    $('body').addClass("loading"); 
})


$(document).ready(function () {     


   var preloadi = [
        ['selector1','WCMSWR/_assets/images/images/1.png'],
        ['selector2','WCMSWR/_assets/images/images/2.png'],
        ['selector3','WCMSWR/_assets/images/images/3.png']
   ];



    preload(preloadi);
});

3 个答案:

答案 0 :(得分:2)

尝试这一点(这完全取决于逻辑):

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $(this[0]).src = this[1];
    });
    $('body').removeClass("loading"); 
}
$(function() { 
    $('body').addClass("loading"); 
};
///
/// elsewhere
///

///I'm also updating your array call because it doesn't make much sense, sadly to me
///otherwise you're overwiting all images with the same image every time. 
///I think it makes much more sense to have a set of hidden images in the 
/// footer of the page so the browser keeps them in memory/cache
$(document).ready(function () {
   preload([
        ['selector1','WCMSWR/_assets/images/images/1.png'],
        ['selector2','WCMSWR/_assets/images/images/2.png'],
        ['selector3','WCMSWR/_assets/images/images/3.png']
   ]);
 });

所以,onload你正在添加加载类,然后一旦你完成加载,那么你将删除该类作为你做的最后一件事。

但是,表面上看,我会更像这样构造:(假设jQuery的当前版本[&gt; = 1.8])

function loadSomeImages(arrayOfImages){
  $.Deferred(function(){

    $('body').addClass("loading"); 

  }).then(function(){

    $(arrayOfImages).each(function(){
      $(this[0]).src = this[1];
    });

  }).done(function(){

    $('body').removeClass("loading"); 

  }).resolve();
}
///
/// elsewhere
///
$(document).ready(function () {
   preload([
        ['selector1','WCMSWR/_assets/images/images/1.png'],
        ['selector2','WCMSWR/_assets/images/images/2.png'],
        ['selector3','WCMSWR/_assets/images/images/3.png']
   ]);
 });

因为你正在使用deferred's等到每件事都完成了,你就不会把抖动弄糟(你的IE错误),你的代码是干净的,因为你打算发生了什么,你已经以正确的方式订购了东西。

希望这能达到你的目的,并且有所帮助。


我还会敦促你“命名”你的对象。我在下面扩展了前面的例子:

window.sephiith = window.sephiith | {};
window.sephiith.loadSomeImagesDeferred = null;
window.sephiith.loadSomeImages = function loadSomeImages(arrayOfImages){
  sephiith.loadSomeImagesDeferred = $.Deferred(function _startArrayOfImages(){

    $('body').addClass("loading"); 

  });
  sephiith.loadSomeImagesDeferred.then(function _applyArrayOfImages(){

    $(arrayOfImages).each(function(){
      $(this[0]).src = this[1];
    });

  });

  sephiith.loadSomeImagesDeferred.done(function _doneArrayOfImages(){

    $('body').removeClass("loading"); 
    sephiith.loadSomeImagesDeferred = null;
  });
  return sephiith.loadSomeImagesDeferred;
}
///
/// elsewhere
///
$(document).ready(function () {
   preload([
        ['selector1','WCMSWR/_assets/images/images/1.png'],
        ['selector2','WCMSWR/_assets/images/images/2.png'],
        ['selector3','WCMSWR/_assets/images/images/3.png']
   ]);
 }).resolve();

此命名空间可确保您的代码不会干扰“其他人”的代码。虽然看起来有点矫枉过正,但随着时间的推移,这个命名空间是一个很好的方向。您现在还可以看到sephiith.loadSomeImagesDeferred在代码中的其他位置是否有值,因此您可以知道您仍在加载图像,也可以是有用的。也许现在你想完成别的东西

if(sephiith.loadSomeImagesDeferred) /* sanity check to make sure we didn't already null it out */ {
  // TODO: track sephiith.loadSomeImagesDeferred to add a new function #NEWFUNCTION
  sephiith.loadSomeImagesDeferred.then(function _NEWFUNCTION(){ /* do more stuff here */ });
} else {
  console.log( 'sephiith.loadSomeImagesDeferred was already nulled out before #NEWFUNCTION!!' );
}

因此,您可以在页面加载时构建所有这些延期项目,这样当您点击loadSomeImages(things);时,您将在完成之前启动所有这些项目。

我意识到Deferred可能是一个很大的新事物,所以如果它没有意义,不用担心,但这会使你的代码更加有意识你想要发生。另请注意,我已经确保告诉自己我想添加其他内容,但#NEWFUNCTION没有及时添加。 (另外,总是命名你的匿名函数。它使堆栈跟踪跟踪变得更加容易。)

所以,最后一个例子实际上有点复杂。我在它上面添加了一个HR,以便更容易在我“跳鲨鱼”的地方。 而且因为我是一个肛门开发人员,他想让事情变得更清洁... 这里有一些更多的改进,希望这个代码进展有意义:


window.sephiith = window.sephiith | {};
sephiith.loadSomeImagesDeferred = null;
sephiith._startArrayOfImages = function _startArrayOfImages(){
    $('body').addClass("loading"); 
};
sephiith._doneArrayOfImages = function _doneArrayOfImages(){

    $('body').removeClass("loading"); 
    sephiith.loadSomeImagesDeferred = null;
    sephiith._ArrayOfImages = {};
};
sephiith._ArrayOfImages = {};
sephiith._applyArrayOfImages = function _applyArrayOfImages(){

    $(sephiith._ArrayOfImages).each(function(){
      $(this[0]).src = this[1];
    });

};

sephiith.loadSomeImages = function loadSomeImages(arrayOfImages){
  sephiith._ArrayOfImages = arrayOfImages;

  sephiith.loadSomeImagesDeferred = $.Deferred(sephiith._startArrayOfImages);

  sephiith.loadSomeImagesDeferred.then(sephiith._applyArrayOfImages);

  sephiith.loadSomeImagesDeferred.done(sephiith._doneArrayOfImages);
  return sephiith.loadSomeImagesDeferred;
}
///
/// elsewhere
///
$(document).ready(function () {
   preload([
        ['selector1','WCMSWR/_assets/images/images/1.png'],
        ['selector2','WCMSWR/_assets/images/images/2.png'],
        ['selector3','WCMSWR/_assets/images/images/3.png']
   ]).resolve();
 });

///
/// elsewhere
/// notice we're still loading the page, so we haven't called the onready of the preload
///
if(!sephiith._newFunction) {
  sephiith._newFunction = function _NEWFUNCTION(){ /* do more stuff here */ console.log(sephiith._ArrayOfImages); };
} else {
  console.log('sephiith._newFunction was already defined, not defining again');
}


if(sephiith.loadSomeImagesDeferred) {
  // TODO: track sephiith.loadSomeImagesDeferred to add a new function #NEWFUNCTION
  sephiith.loadSomeImagesDeferred.then(sephiith._newFunction);
} else {
  console.log( 'sephiith.loadSomeImagesDeferred was already nulled out before sephiith._newFunction could be added!!' );
}

后记:我没有对此进行测试,我基于你想要的东西基本上是从我的工作空间写的,所以我可能会有一些错误,但这应该有效地做你想要的。

答案 1 :(得分:0)

为什么不把所有内容放在一个匿名函数中?正常情况下请致电preload()

$(function() { 
    $('body').addClass("loading"); 

    function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){
            $('<img/>')[0].src = this;
        });
    }

    $('body').removeClass("loading"); 

});

答案 2 :(得分:0)

$(document).ready(function () {     
    var preload = [
           'WCMSWR/_assets/images/images/1.png',
           'WCMSWR/_assets/images/images/2.png',
           'WCMSWR/_assets/images/images/3.png'
    ];

    function preload(arrayOfImages) {
        $('body').addClass("loading");
        $(arrayOfImages).each(function(){
            $('<img/>')[0].src = this;
        });
        $('body').removeClass("loading");
    }

    preload(preload);
});