简体   繁体   English

enquire.js-如何在动态创建的寄存器函数中维护变量?

[英]enquire.js - How to maintain variables in dynamically created register functions?

I'm looping through an object containing multiple elements, with each containing multiple media queries. 我正在遍历包含多个元素的对象,每个对象包含多个媒体查询。

In the loop, I'm dynamically calling enquire.js .register() to perform something on the match. 在循环中,我正在动态调用enquire.js .register()在比赛中执行某些操作。 This works initially, but outside of the loop, and upon resizing the browser, the matches no longer work, as the variables used in the loop have been incremented to their hightest value from the loop. 此操作最初有效,但在循环之外,并且在调整浏览器大小后,匹配不再起作用,因为循环中使用的变量已从循环中增加到最高值。

It's probably easier to explain in code! 用代码解释可能更容易!

Here's the images object: 这是images对象:

var images = [
   {
      "selector":"[data-id=\"0\"]",
      "breakpoints":[
         {
            "mediaquery":"(max-width: 31.25em) ",
            "src":"image-0-small.jpg"
         },
         {
            "mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
            "src":"image-0-medium.jpg"
         },
         {
            "mediaquery":"(min-width: 46.3125em) ",
            "src":"image-0-large.jpg"
         }
      ]
   },
   {
      "selector":"[data-id=\"1\"]",
      "breakpoints":[
         {
            "mediaquery":"(max-width: 31.25em) ",
            "src":"image-1-small.jpg"
         },
         {
            "mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
            "src":"image-1-medium.jpg"
         },
         {
            "mediaquery":"(min-width: 46.3125em) ",
            "src":"image-1-large.jpg"
         }
      ]
   },
   {
      "selector":"[data-id=\"2\"]",
      "breakpoints":[
         {
            "mediaquery":"(max-width: 31.25em) ",
            "src":"image-2-small.jpg"
         },
         {
            "mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
            "src":"image-2-medium.jpg"
         },
         {
            "mediaquery":"(min-width: 46.3125em) ",
            "src":"image-2-large.jpg"
         }
      ]
   }
];

And here's the loop: 这是循环:

for (var x=0; x < images.length; x++) {
  for (var y=0; y < images[x]['breakpoints'].length; y++) {
    enquire.register(images[x]['breakpoints'][y]['mediaquery'], function () {
      // x and y unfortuntaley equal 3 & 3 after the loop, so how do I maintain them from inside the match?
      // Interestingly, Firefox doesn't seem attempt to fire matches more than once. Chrome and IE 11 do, which is where I found the error that images[x] is undefined

      console.log('match-index', x, y);
      console.log('match-images', images);
      console.log('match-mediaquery', images[x]['breakpoints'][y]['mediaquery']);
    });
  }
}

images[x] is undefined because x = 3 . images[x]是未定义的,因为x = 3 How do I keep x and y to equal what was originally passed in on future match es? 如何使xy等于将来match es中最初传递的值?

Variable scope is maintained at the function level. 可变范围在功能级别上维护。 So you have to find a way to create a copy of the variables at each iteration and pass that copy to the registration function. 因此,您必须找到一种在每次迭代时创建变量副本并将该副本传递给注册函数的方法。

One way to do that is to create an immediately-executing function expression that returns the function that will eventually be executed by register() . 一种实现方法是创建一个立即执行的函数表达式,该表达式返回最终将由register()执行的函数。

It would look something like this: 它看起来像这样:

(function(innerX, innerY) {
    return function() {
        // use innerX and innerY here
    };
}(x, y))

The way this works is that the immediately-executing function expression creates a closure for the function that it returns, which has a reference to the x and y copies - innerX and innerY. 这种工作方式是立即执行的函数表达式为其返回的函数创建一个闭包,该闭包引用了x和y副本-innerX和innerY。

The marvellous @WickyNilliams taught me about closures and provided the following working code: 很棒的@WickyNilliams教给我有关闭包的知识,并提供了以下工作代码:

function registerWithEnquire(x, y) {
    enquire.register(swapImages[x]['breakpoints'][y]['mediaquery'], function () {
        // I want to set the src of the relevant cloned image to its corresponding src property in the swapImages object with:

        //document.querySelector(swapImages[x]['selector']).src = swapImages[x]['breakpoints'][y]['src'];

        // x and y unfortuntaley equal 5 & 3 after the loop, so how do I maintain them from inside the match?

        // Interestingly, Firefox doesn't seem attempt to fire matches more than once. Chrome and IE 11 do, which is where I found the error that swapImages[x] is undefined

        console.log('match-index', x, y);
        console.log('match-swapImages', swapImages);
        console.log('match-mediiquery', swapImages[x]['breakpoints'][y]['mediaquery']);

    });
}

for (var x=0; x < swapImages.length; x++) {
    console.group(x);
    console.log(swapImages[x]['selector']);

    for (var y=0; y < swapImages[x]['breakpoints'].length; y++) {
        console.log(swapImages[x]['breakpoints'][y]['mediaquery']);

        registerWithEnquire(x, y);
    }

    console.groupEnd();
}
console.log(x, y);

A working pen can be found here: http://codepen.io/WickyNilliams/pen/ckEeD 可以在这里找到一支工作笔: http : //codepen.io/WickyNilliams/pen/ckEeD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM