1

I have this code:

function setSidebar(visible) {
    "use strict"
    if (visible === "show") {
        $("#sidebar-width-switch").prop('title', 'Hide Sidebar');
        $("#sidebar").show();
    } else {
        $("#sidebar-width-switch").prop('title', 'Show Sidebar');
        $("#sidebar").hide();
    }
}

With typescript I have seen a lot more use of classes. In this case would it be more easy to maintain if functions like this were implemented as classes and if so then how would I do this and how would I call the class?

Here is how I call this now:

    $('#sidebar-width-switch')
        .click(function (e) {
            if ($("#sidebar").is(':hidden')) {
                setSidebar("show");
                localStorage.setItem('Sidebar', 'show');
            } else {
                setSidebar("hide");
                localStorage.setItem('Sidebar', 'hide');
            }
        });
4

2 に答える 2

1

A class would allow you to separate the data from the behaviour, a bit like this:

class SideBar {
    private sidebarElement: JQuery;
    private switchElement: JQuery;

    constructor(sidebarId: string, switchId: string) {
        this.sidebarElement = $('#' + sidebarId);
        this.switchElement = $('#' + switchId);
    }

    show() {
        this.sidebarElement.show();
        this.switchElement.prop('title', 'Hide Sidebar');
    }

    hide() {
        this.sidebarElement.hide();
        this.switchElement.prop('title', 'Show Sidebar');
    }
}

var sidebar = new SideBar('sidebar', 'sidebar-width-switch');
sidebar.show();
sidebar.hide();

This would allow you to use the SideBar class without it being welded to the specific ID and it would allow you to have multiple sidebars on the page, each one being a new SideBar.

The constructor ensures that you set up the class with the required data, which means the methods don't need to accept arguments. This reduces repetition in the calling code.

The class is re-usable in many projects, the function is tightly coupled to the specific HTML implementation (the specific ids).

于 2012-11-14T17:14:30.003 に答える
-2

関数としてカプセル化しておく方がよいでしょう。

理解するコードが少なく、使用する儀式も少なくなります。

于 2012-11-16T11:58:58.573 に答える