Search code examples
javascriptwechatwechat-miniprogram

Simpler way to bind onTap functions to buttons in WeChat mini-program


I'm creating a simple audio playing app for WeChat. On the play screen, it has 5 control buttons - prev, fast backward, play/pause, fast forward, and next. So I created them and binded to each event listening functions.

<!-- part of play.wxml -->

<view class="button-group">
    <image class="button" src="../../res/img/control_prev.svg" bindtap="onPrev"></image>
    <image class="button" src="../../res/img/control_fback.svg" bindtap="onFBack"></image>
    <image class="button" src="../../res/img/control_play.svg" bindtap="onPlay"></image>
    <image class="button" src="../../res/img/control_ffor.svg" bindtap="onFFor"></image>
    <image class="button" src="../../res/img/control_next.svg" bindtap="onNext"></image>
</view>

On play.js, I had to define all those 5 functions.

/* part of play.js */

onPrev: (event) => {
    Player.prev()
},
onFBack: (event) => {
    Player.fback()
},
onPlay: (event) => {
    Player.play()
},
onFFor: (event) => {
    Player.ffor()
},
onNext: (event) => {
    Player.next()
},

I think there must be a better way to simplify this repeated code. How can I make them as one function and bind it to multiple buttons?


Solution

  • Make a function for it and pass a id for each button using data-* property.

    For example,

    <image class="button" src="../../res/img/control_prev.svg" bindtap="onTap" data-id="prev"></image>
    <image class="button" src="../../res/img/control_fback.svg" bindtap="onTap" data-id="fback"></image>
    ...
    
    onTap: (event) => {
        let id = event.currentTarget.dataset.id
        if (id == "prev")
            Player.prev()
        else if (id == "fback")
            Player.fback()
        ...