Variable scope and updating array

slickCall = {
      slidesToShow: 1,
      accessibility: true,
      dots: true,
      arrows: true,
      autoplay: _.autoplay,
      pauseOnHover: false,
      adaptiveHeight: true,
      initialSlide: _.randomize ? randomizeSlideshow() : 1 // undefined if _.randomize =  true
    };
    setTimeout(function() {
      console.log(slickCall);//shits still returning undefined
    },4000);
    function randomizeSlideshow() {
      console.log("this got to run");
      var math;
      $.getJSON(_.url).done(function (data) {
        math = parseInt(Math.ceil(Math.random() * data.objects.length));
        console.log(math + " :first"); // 1-8 depending...all good here
        return math;
      });
      console.log(math + " :final"); // undefined
    };

I’m trying to get the initialSlide setting to get a random value. In this instance, _.randomize is true, and is supposed to return a value from 1-8 (data.objects.length). It’s always undefined though. What can I do?

This isn’t how you do things asynchronously. You’re always going to get undefined, because you’re never going back and updating the original object. The object declaration isn’t going to hang around waiting for initialSlide to be defined.

So what do you recommend?

You need to update slickCall.intialSlide when getJSON is done. It’s going to take a total restructure of the way you’re trying to do this.

Well I had tried updating the object like this but when slick gets called, it still isn’t using the new initialSlide value

function randomizeSlideshow() {
      console.log("this got to run");
      var math;
      $.getJSON(_.url).done(function (data) {
        math = parseInt(Math.ceil(Math.random() * data.objects.length));
        console.log(math + " :first"); // 1-8 depending...all good here
        slickCall["initialSlide"] = math;
        console.log(slickCall);
      });
    };

Got it

slickCall = {
      slidesToShow: 1,
      accessibility: true,
      dots: true,
      arrows: true,
      autoplay: _.autoplay,
      pauseOnHover: false,
      adaptiveHeight: true,
      initialSlide: _.randomize ? randomizeSlideshow() : 1
    };
    function randomizeSlideshow() {

      $.getJSON(_.url).done(function (data) {
        slickCall["initialSlide"] = parseInt(Math.ceil(Math.random() * data.objects.length));
        startInit();
      });

    };

    _.defaults set here blah blah

    function startInit() {
      _.settings = $.extend(true, {}, _.defaults, options);
      _.init();
    };

    if(!_.randomize) {
      startInit();
    }
3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.