How do you reference a variable from inside an event listener?

You must Login before you can answer or comment on any questions.

I have the following scenario, and I would like to be able to use the array inside the event listener:

var array = [];
array.push( { id:1, value:"1", desc:"abc" } );
 
button.addEventListener('click', function( array ){
    alert( this.array.length );
});
How do I reference the array from inside the Event Listener, as this code is not functional?

Thanks guys....

1 Answer

Accepted Answer

You are just doing a simple mistake here. as long as the eventListener are in the same block or in same scope you can do like this

var array = [];
array.push( { id:1, value:"1", desc:"abc" } );
 
button.addEventListener('click', function( ){
    alert( array.length );
});

— answered 12 months ago by Ajeet pratap Maurya
answer permalink
5 Comments
  • Hey thanks for that!! I have the contents of this array displayed in a scrollview:

    var scroller = Ti.UI.createScrollView({
        contentHeight:'auto',
        height:120
    });
    win.add(scroller);
    var container = Ti.UI.createView({
        layout:'vertical',
        height:'auto'
    });
    scroller.add(container);
    If I pushed another row into the array from within the eventlistener, how do I now update the contents of this scrollview??

    — commented 12 months ago by Donal Lynch

  • you just have to add that new row to scrollView. i.e. scroller.add('your new row');

    — commented 12 months ago by Ajeet pratap Maurya

  • one quick question here, your array contain what type of data??

    — commented 12 months ago by Ajeet pratap Maurya

  • Show 2 more comments

Your Answer

Think you can help? Login to answer this question!