javascriptyandex-maps

how to attach data to a button?


I add custom button to map. This button display on left top position of screen.

JSFIDDLE demo here.

I need attach data to button. In my code I add a number to the button. After clicking I would like to display this number in console. Please help me.

JS:

ymaps.ready(init);

var map;

function init(){     
    map = new ymaps.Map("map", {
        center: [12.12, 12.12],
        controls: [],
        zoom: 5
    });  

    var btn = new ymaps.control.Button({
        data: {
            content: "bla",
            num: 77783
        }
    });

    map.controls.add(btn, {
        float: 'left',
    }); 

    btn.events.add('click', (e) => {
        console.log('binded data is:', e.get('num'))
    });    
};

Solution

  • You need to change this function:

    btn.events.add('click', (e) => {
        console.log('bound data is:', e.get('num'))
    });   
    

    to:

    btn.events.add('click', (e) => {
        console.log('bound data is:', e.originalEvent.target.data.get('num'))
    });
    

    The updated fiddle