2

I'm new to Javascript. I'm trying to create a slider that uses a callback function to display a string; to be precise, options.data is an array of strings and i need to use the input from the slider to print the correct string from it. When i run the script, the _getString method is undefined, so it didn't work. How can i achieve this?

function Obj( options ) {

this.opz1 = options.opz1;
this.opz2 = options.opz2;
this.data = options.data;   // Data is an Array..

this._getString = function( val ) {

  return 'Value: ' +this.data[val].label;
};

this.update = function () {

  console.log("Using slider!");
};  

this.init = function () {

  var sliderCfg = {

    position: 'position!',
    printValue: this._getString,
    width: '300px',
    value: 0
  };

  var slider = new Slider( update, this.sliderCfg );

  };

  this.init();
}

var a = new Obj( opz );

Edit: jQuery.Deferred exception: Cannot read property 'label' of undefined TypeError: Cannot read property 'label' of undefined

Edit2: a simplified scenario with the same issue > https://jsfiddle.net/nhzm8ctt/

var array = [ 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10'];

config = {

  "data": array,
  "funzione": 'boh'
};
 
function Obj ( options ) {

  this.data = options.data;

  this._getString = function ( val ) {
 
    return 'Output is: ' +this.data[0];
  };

  this.init = function () {

    var anotherObj = new AnotherObj( this._getString );
  };

  this.init();
}

function AnotherObj( f ) {

  this.init = function () {

    var value = 0;

    console.log( "f: ", f(value) );
  };

  this.init();
}

var prova = new Obj( config );
melpomene
  • 84,125
  • 8
  • 85
  • 148
nwdom
  • 77
  • 2
  • 8
  • 1
    Should be `printValue: this._getString()` – Alon Eitan Jan 21 '17 at 21:48
  • You don't have `sliderCfg` defined as property on the `Obj` instance, just as a local variable inside `init`. Initiate `Slider` using `var slider = new Slider( update, sliderCfg );` – Rafael Jan 22 '17 at 09:45
  • Also 'this.data[val].label' seems to be undefined.. – nwdom Jan 22 '17 at 09:47
  • I added a jsfidle with a simplified scenario... I hope it will help to explain my doubts! – nwdom Jan 22 '17 at 19:18
  • @nwdom Can be simplified to: `var obj = { data: 42, foo: function () { return this.data; } }; var f = obj.foo; f()` – melpomene Jan 22 '17 at 19:22
  • This is definitely a duplicate. http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback?rq=1 maybe? – melpomene Jan 22 '17 at 19:24
  • @melpomene i think i can't simplify because i need my slider into the first object.. I read this thread http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback?rq=1, but it still did't work and i still have my doubts – nwdom Jan 22 '17 at 19:45

0 Answers0