javascript - 如果在对象中定义则覆盖函数,否则默认功能

标签 javascript typescript

我有 calendar 小部件,它是用 TypeScript 编写的。我可以将监听器绑定(bind)到单独的函数,但我希望这个单独的函数具有默认功能,直到有人覆盖传递给构造函数的 config 对象中的函数。在构造函数中,我传递了类似的东西

{
  container: 'xxx',
  cellClick: function(sender, event, data) {
    // custom functionality
  }
}

我如何在我的基类中定义函数 cellClick 以及当我呈现我的 td 单元格以将事件监听器绑定(bind)到此函数并为单元格传递一些数据时将具有单元格的一些默认功能,但如果有人在对象中定义了函数,则用单击的单元格的数据覆盖它。

我的做法与此类似,但这会将监听器直接绑定(bind)到 config 函数。我敢打赌在我的 setter 中做到这一点真的很容易,但我不知道怎么做。

td.addEventListener('click', function () {
  this.config.cellClick(td, event, data);
})

编辑: 这是我的 abstract 类,它扩展了 Table 类,它只是为 thead、tbody 和 tfoot

创建对象
defaultConfig = {
                container: '',
                dataSource: [],
                currentDate: new Date(),
                currentView: 'month',
                views: [
                    { type: 'Day' },
                    { type: 'Week' },
                    { type: 'Month' }
                ],
                startDayHour: 8,
                endDayHour: 20,
                cellDuration: 60,
                todayHighlight: true,
                cellClick: this.cellClick,
                eventClick: this.eventClick,
                showAllDayPanel: false,
                disabledDays: [],
                resources: {
                    dataSource: [],
                    field: null
                },
                groupBy: null,
            }

            set config(cfg: my.core.calendar.iCalendarConfiguration) {
                if (cfg) {

                    for (var key in cfg) {
                        if (cfg[key] == null) {
                            cfg[key] = this.defaultConfig[key];
                        }
                    }

                    if (cfg.cellClick != null) {
                        cfg.cellClick.bind(this.cellClick);
                    }

                    this.configuration = cfg;
                    this.MonthLength = new Date(cfg.currentDate).getMonth();
                    this.weekDayStart = cfg.currentDate;
                    this.weekDayEnd = cfg.currentDate;
                }
            }

            get config(): iCalendarConfiguration {
                return this.configuration;
            }

            .............

            constructor(config: iCalendarConfiguration) {
                super();

                this.element.className = "table table-bordered table-responsive col-sm-12"; // could be readed from config but tbd
                this.config = config;
                this.appointmentsArray = config.dataSource;
                this.tools = new my.calendar.CalendarTools();

                /**
                 *  Append the element to the container
                 *  which is defined in the config.
                 */
                document.getElementById(config.container).appendChild(this.tools.createDiv('', 'row', this.parentID)).appendChild(this.element);
            }

            abstract createCalendar();

            abstract bindAppointments(view: string);

            abstract Next(sender, e, data)

            abstract Previous(sender, e, data)

            abstract TabClick(sender: any, event: any, data: any)

            abstract initialize()

            abstract onResize()

            abstract cellClick(sender: any, event: any, data: any)

            abstract eventClick(sender: any, event: any, data: any)

还有一个 calendar 类扩展了抽象类及其用配置对象实例化的类。

export class Calendar extends my.core.calendar.CalendarTable {
        weeklyView: my.calendar.WeeklyView;
        monthlyView: my.calendar.MontlyView;
        dayView: my.calendar.DayView;

        constructor(cfg: my.core.calendar.iCalendarConfiguration) {
            super(cfg);

            this.weeklyView = new my.calendar.WeeklyView(this);
            this.monthlyView = new my.calendar.MontlyView(this);
            this.dayView = new my.calendar.DayView(this);
        }


        onResize() {
            /**
             *  Repaint all appointments on window resize
             *  For many reasons
             */
            this.bindAppointments();
        }

        createCalendar() {

            /** Clear everything on change */
            if (this.tBody.rows.length > 0) {
                this.tBody.clear();
                this.tHead.clear();
            }

            switch (this.config.currentView) {
                case "month":
                    this.monthlyView.createMontlyView();
                    break;
                case "day":
                    this.dayView.createDayView();
                    break;
                case "week":
                    this.weeklyView.createWeeklyView();
                    break;
            }

            this.bindAppointments();
        }

        bindAppointments() {
            /** Remove the events div for week/day view. Its here because reasons. */
            if (this.element.parentElement.querySelector("#events") !== null) {
                let child = document.getElementById('events');

                this.element.parentElement.removeChild(child);
            }

            switch (this.config.currentView) {
                case "month":
                    this.monthlyView.bindMonthAppointments();
                    break;
                case "day":
                    this.dayView.bindDayAppointments();
                    break;
                case "week":
                    this.weeklyView.bindWeekAppointments();
                    break;
            }
        }

        Next(sender, e, data) {
            switch (this.config.currentView) {
                case "month":
                    this.monthlyView.monthNavigationChange(true);
                    break;
                case "day":
                    this.dayView.dayNavigationChange(true);
                    break;
                case "week":
                    this.weeklyView.weekNavigationChange(true);
                    break;
            }
            this.createCalendar();
            this.updateLabels();
        }

        Previous(sender, e, data) {
            switch (this.config.currentView) {
                case "month":
                    this.monthlyView.monthNavigationChange(false);
                    break;
                case "day":
                    this.dayView.dayNavigationChange(false);
                    break;
                case "week":
                    this.weeklyView.weekNavigationChange(false);
                    break;
            }
            this.createCalendar();
            this.updateLabels();
        }

        TabClick(sender: any, event: any, data: any) {

            switch (sender.id.toLowerCase()) {
                case "day":
                    this.tools.setActiveTab(this, 'day', event);
                    // update currentdate
                    break;
                case "month":
                    this.tools.setActiveTab(this, 'month', event);
                    // update currentdate
                    break;
                case "week":
                    this.tools.setActiveTab(this, 'week', event);
                    // update currentdate
                    break;
            }
            this.createCalendar();
            this.updateLabels();
        }


        updateLabels() {
            let date = new Date(this.config.currentDate);
            switch (this.config.currentView) {
                case "month":
                    this.currentDateMonth.value = String(this.calendar_months_label[date.getMonth()]) + ' ' + String(date.getFullYear());
                    break;
                case "day":
                    this.currentDateMonth.value = String(this.config.currentDate.getDate()) + ' ' + String(this.calendar_months_label[this.config.currentDate.getMonth()]) + ' ' + String(this.config.currentDate.getFullYear());
                    break;
                case "week":
                    this.currentDateMonth.value = String(this.tools.getPreviousWeekStr(this.weekStart, this.weekEnd, this.calendar_months_label[this.config.currentDate.getMonth()], this.config.currentDate.getFullYear()));
                    break;
            }
        }

        initialize() {
            this.tools.createNavigation(this, this.config);
            this.createCalendar();
            this.bindAppointments();
        }

        cellClick(sender, event, data) {
            console.log('fired up from mycalendar');
        }

        eventClick(sender, event, data) {

        }

    }; // end class basic

view 渲染、逻辑等还有 3 个类,它们获取表对象并执行一些操作。

下面是我如何初始化它。

var calendar = new my.calendar.Calendar({
        container: 'calendarTestContainer',
        dataSource: data,
        views: [
            { type: 'Week' },
            { type: 'Day' },
            { type: 'Month' }
        ],
        currentDate: new Date('2017-03-15'),
        currentView: 'week',
        startDayHour: 8,
        disabledDays: [6],
        cellDuration: 30,
        resources: {
            dataSource: staffs,
            field: 'UID'
        },
        endDayHour: 24,
        cellClick: function (sender, e, data) {
            // this has to be overrided
        },
        showAllDayPanel: true
    }).initialize();

因为我不是真正的 OOP 我愿意接受重构建议。

最佳答案

您可以提供一个带有默认函数的默认对象:

defaults = {
    option1: 'value1',
    cellClick: function() {/*do your default stuff here*/}
}

当您拥有配置对象时,您可以使用 Object.assign 合并它们:

Object.assign(defaults, config || {});

您的 defaults 对象现在包含所有默认值,除非您的 config 对象中有值。现在你可以使用

td.addEventListener('click', defaults.cellClick)

这会将您的默认函数或覆盖函数添加为处理程序。

关于javascript - 如果在对象中定义则覆盖函数,否则默认功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175212/

相关文章:

javascript - 模糊验证的 jquery

javascript - 如何使用 Angular 动态更改css类

javascript - 我如何在 Facebook 的社交插件中检查此人是否喜欢 Facebook 页面?

javascript - 如何为新库编写 typescript 定义文件?

javascript - 如果 ajax 完成,则将 html 替换为请求的数据

javascript - 放置 Javascript 片段以在呈现之前更改页面的 DOM 的最佳位置在哪里

angular - 如何从 Angular 6 中的 Promise 对象中获取数据/值?

javascript - 是否需要包含 Typescript 的 java lint 提示,VS - 2013

javascript - VSCode 仅在导入到某处时才通过相应的 Foo.d.ts 为 Foo.js 提供智能感知;如何在 Foo.js 本身中启用智能感知?

javascript - 从 Map.values() 选择一个属性