How to create reusable code with methods ?

Oct 16 2018 2:18 AM

Hi,
How to create a method for the reuse in two parts ?
I have a google map, and I have a code that displays the information of a marker when it clicks on it, the codes are almost the same, the variables only differ.

Example: In the first part, I have displayed 5 markers, click on them and the information is displayed:
marker.addListener('click', () => {
//create the content
let markerInfoTemplate = `
<span class="title">${this.locations[i][0]}</span><br>
<span class="address">${this.locations[i][3]}</span><br>
<button class="text-button">
<a href="${this.locations[i][4]}">Show route</a>
</button>
`;
this.infowindow.setContent(markerInfoTemplate);
this.infowindow.open(map, marker);

//change the markers icons
this.deselectAllMarkers();
marker.setIcon(this.activeIcon);
});

the 2nd Code, when looking for ex "catering" and several markers are displayed:
currentMarker.addListener('click', () => {
//create the content
let markerInfoTemplate = `
<span class="title">${place.name}</span><br>
<span class="address">${place.adr_address}</span><br>
<button class="text-button">
<a href="${place.url}">Show route</a>
</button>
`;

this.infowindow.setContent(markerInfoTemplate);
this.infowindow.open(map, currentMarker);

//change the markers icons
this.deselectAllMarkers();
currentMarker.setIcon(this.activeIcon);
});

This part would like to reuse it :
let markerInfoTemplate = `
<span class="title">${place.name}</span><br>
<span class="address">${place.adr_address}</span><br>
<button class="text-button">
<a href="${place.url}">Show route</a>
</button>
`;

As I said, the code is the same, except the variables. How can I restructure the code so it is not duplicated? Should I do a method? How could I do that? Thank you!


Answers (1)