preloader
心得

Make Toggle Feature More Reusable and Influential | 讓你的開關功能更易重複使用和影響力

Make Toggle Feature More Reusable and Influential | 讓你的開關功能更易重複使用和影響力

Share my opinion to toggle feature such as toggleCard() and toggleBtn. I provide a better way using such as setShowCardContentBy() or setShowCardContentTo() to create it. It will be useful at scenarios about pages, which are companied with this kind feature, grow with more features or elegant user experiences. It’s welcome to share it and used in your daily work.

In many tutorials, it’s common to see an example about toggle feature with a button. For example, there is a buttton can show and hide a card after clicking that. Below are assumed in Angular and typescript environment, you can adapt them to your own environment.

list-of-item-card.ts:

// ...excerpted

toggleCardDetail() {
    this.isShowCarddetail = !this.isShowCarddetail
}
    

list-of-item-card.html:

<!-- ...(excerpted) -->

<button (click)="toggleCardDetail()">
    {{ isShowCarddetail ? 'HIDE_DETAIL' : 'SHOW_DETAIL'}}
</button>

<!-- merchandise 1 -->
<div class="card">
    <div class="card-header">
        {{ title1 }} - ${{ price1 }}
    </div>

    <div class="card-detail" *ngIf="isShowCarddetail">
        <!-- &#37; means % -->
        {{ percentOfThumpup1 }} &#37; give thump up
    </div>
</div>

<!-- merchandise 2 -->
<div class="card">
    <div class="card-header">
        {{ title2 }} - ${{ price2 }}
    </div>

    <div class="card-detail" *ngIf="isShowCarddetail">
        <!-- &#37; means % -->
        {{ percentOfThumpup2 }} &#37; give thump up
    </div>
</div>

I recommmend to change toggleCardDetail() to setShowCardDetailBy(targetVal) because it will become more reusable and directly mean what you want this function do. This way well uses parameter concept of a function.

rewrited content of list-of-item-card.ts:

setShowCardDetailBy(targetVal: boolean) {
    this.isShowCarddetail = targetVal

    /**
     *  and you can do everything/side-effect you want to do
     *  here after changing the variable: isShowCarddetail
     */
}
<!-- ...(excerpted) -->

<button (click)="setShowCardDetailBy(!isShowCarddetail)">
    {{ isShowCarddetail ? 'HIDE_DETAIL' : 'SHOW_DETAIL'}}
</button>

The better version of function makes itself more reusable. As product growing and it might be added more features relating with that function in the future such as for improving user experience. Some coworker colleague might praise this function is so reusable in mind or pull-request review that he/she can quickly finish his/her workload or use it to build more complicated/elegant features. In the same time, the function author will gain reputation and increase his/her influence betweeen colleagues.