0

I am trying to use enquire.js to trigger a reload of my bxslider when the screen size is small, to show fewer images.

I have registered a screen width as below.

enquire.register("screen and (max-width:900px)", {
    match: this.ChangeSliderDown,
    unmatch:this.ChangeSliderUp
});

Now as part of the transition i need to do a calculation based on a variable that is associated with the Prototype of the current class.

ChildCarousel.prototype = {
  ...

    ChangeSliderUp: function()
    {
        var maxSlides = (this.ourCarouselCollection.length < 3) ?  1 : 3;
            ...
    }
}

in all my other functions referring to this allows me to access variables such as the ourCarouselCollection in the instance of enguire js i get the object that is a result of the register call.

why is this happening and is it possible to change it?

Bluephlame
  • 3,901
  • 4
  • 35
  • 51
  • 1
    duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback). Notice that this is not enquirejs-specific – Bergi Jan 30 '14 at 02:34
  • That was able to teach me more about this, I found the bind() method in the above question and that solved the problem – Bluephlame Jan 30 '14 at 02:42

2 Answers2

3

adding the bind(this method solved the problem

enquire.register("screen and (max-width:900px)", {
    match: this.ChangeSliderDown.bind(this),
    unmatch:this.ChangeSliderUp.bind(this)
});
Bluephlame
  • 3,901
  • 4
  • 35
  • 51
1

The value of this has nothing to do with scope, it is resolved within an execution context and is set by the call or with bind. Also, it is convention that only functions that are intended to be called as constructors have names that start with a capital letter (so ChangeSliderUp should be changeSliderUp).

The ChangeSliderUp method is expecting to be called with this referencing an instance of ChildCarousel as its this. When you assign a reference to the function like:

match: this.ChangeSliderDown

then the function will be called without this being set to the instance and will default to the global object or be undefined in strict mode.

You can use bind per Bluephlame's answer, or use a closure something like:

// Assuming that this referenes an instance of ChildCarousel
// where this code is running
var carousel = this;

enquire.register("screen and (max-width:900px)", {
    match: function() {carousel.ChangeSliderDown();},
    unmatch: function() {carousel.ChangeSliderUp();}
});

but I can't test that. It should ensure that the function is called as a method of an instance, hence setting this to the instance.

RobG
  • 142,382
  • 31
  • 172
  • 209