Menu
CoddyTech

פולטי אירועים

חלק מהיחידה יסודות Node.js במסלול ה-Node.js של Coddy. שיעור 20 מתוך 24.

החנות צריכה להודיע שנוספה הערה, בלי לדעת מי רוצה לשמוע עליה.

EventEmitter מתוך node:events שומר רשימת מאזינים לכל שם של אירוע. on(name, fn) מוסיף מאזין; emit(name, ...args) קורא לכל המאזינים של אותו שם מיד, עם הארגומנטים האלה. מאזין שנוסף אחרי הקריאה ל-emit לא ישמע דבר.

import { EventEmitter } from 'node:events';

const door = new EventEmitter();
door.on('open', (who) => console.log(`${who} came in`));
door.on('open', () => console.log('Ding!'));
door.emit('open', 'Ada');
// Ada נכנסה, ואז Ding!

כדי להפוך אובייקט קיים לפולט אירועים, מעתיקים אליו את השיטות שלו: Object.assign(new EventEmitter(), { ... }).

challenge icon

אתגר

קל
  • הפוך את store לפולט אירועים שפולט את added עם הטקסט והמספר של ההערה לאחר השמירה.
  • notes.js מאזין ל־added ומדפיס Saved note 4. מתוך המאזין.

הרץ את node notes.js add Buy bread. לאחר מכן השתמש ב־clear והוסף שתי הערות כדי לראות את המספרים מתחילים שוב.

נסו בעצמכם

import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';

const file = 'notes.json';

const readJson = async (name, fallback) => {
    if (!existsSync(name)) {
        return fallback;
    }
    try {
        return JSON.parse(await readFile(name, 'utf8'));
    } catch (err) {
        console.error(`${name} is damaged: ${err.message}`);
        process.exit(1);
    }
};

const [notes, settings] = await Promise.all([readJson(file, []), readJson('settings.json', {})]);

const store = {
    notes,
    settings,
    async save() {
        await writeFile(file, JSON.stringify(this.notes, null, 2));
    },
    async add(text) {
        this.notes.push(text);
        await this.save();
        return this.notes.length;
    },
    async remove(n) {
        const [text] = this.notes.splice(n - 1, 1);
        await this.save();
        return text;
    },
};

export default store;
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה יסודות Node.js