앱 수명 주기 이벤트 관리
애플리케이션이 올바르게 동작하도록 `ready`, `window-all-closed`, `activate`, `quit` 등의 다양한 애플리케이션 수명 주기 이벤트를 처리합니다.
앱 수명 주기 이벤트 관리은(는) CoddyKit의 무료 Electron Desktop App Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Electron Desktop App Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Electron Desktop App Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
App's Journey: Lifecycle Events
Just like people, software applications have a lifecycle! They start, run, and eventually close. In Electron, these stages are managed through "lifecycle events".
- These events let your app react to important moments, like when it's ready to show a window or when all its windows are closed.
- Properly handling them ensures your app behaves predictably and professionally on different operating systems.
Meet the `app` Module
Electron provides a special module called app. This module is the heart of your application's lifecycle management.
- You use the
appmodule to control your application's events. - It allows you to listen for events like when the app is ready, when windows close, or when the app is about to quit.
- It also provides methods to manage the app, such as quitting or restarting.
App is Ready! The `ready` Event
The ready event is the most fundamental lifecycle event. It fires when Electron has finished initializing and is ready to create browser windows and interact with the system.
You must wait for this event before performing most operations. Try running this simple example:
const { app } = require('electron');
app.on('ready', () => {
console.log('Electron app is ready!');
// In a real app, you'd create windows here.
});
// Minimal handler to allow the app to quit when needed
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});Launching Your First Window
The ready event is typically where you create your application's main window. This ensures the Electron environment is fully initialized before the UI appears.
We import BrowserWindow and create an instance, loading simple HTML content directly.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300
});
// Load a simple HTML string directly for a self-contained example
mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Hello Electron!</h1><p>This is your window.</p>');
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});Closing All Windows? `window-all-closed`
The window-all-closed event fires when all of your application's windows have been closed. How you respond depends on the operating system.
- On Windows and Linux, apps usually quit when all windows close.
- On macOS, apps often stay active in the dock.
This code ensures the app quits on Windows/Linux but stays open on macOS.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300
});
mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Close Me!</h1>');
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
// On macOS, it's common for apps to remain active in the dock
// until the user quits explicitly with Cmd + Q.
if (process.platform !== 'darwin') {
app.quit();
}
});Reactivating Your macOS App
The activate event is specific to macOS. It fires when the application is activated, typically when the user clicks on the app's icon in the dock, but no windows are currently open.
This is where you'd re-create a window if mainWindow is null.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300
});
mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Activated!</h1><p>A new window was opened.</p>');
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On macOS, re-create a window when the dock icon is clicked
// and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});Last Chance: `will-quit`
The will-quit event fires just before the application begins to close its windows and quit. This is your last opportunity to perform synchronous cleanup operations.
- For example, you might save unsaved data or close database connections.
- This event is emitted before the
quitevent.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300
});
mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Will Quit Demo</h1>');
mainWindow.on('closed', () => { mainWindow = null; });
}
app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });
app.on('activate', () => { if (mainWindow === null) { createWindow(); } });
app.on('will-quit', (event) => {
console.log('Application is about to quit! Performing final cleanup...');
// event.preventDefault(); // Uncomment to prevent quitting
// Perform synchronous cleanup here, e.g., save data.
});The Final Goodbye: `quit`
The quit event is emitted when the application successfully exits. By this point, all windows have been closed, and the main process is shutting down.
- This event is primarily for logging or very simple, final notifications.
- It's generally too late to perform significant cleanup or prevent the app from quitting.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300
});
mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Quit Demo</h1>');
mainWindow.on('closed', () => { mainWindow = null; });
}
app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });
app.on('activate', () => { if (mainWindow === null) { createWindow(); } });
app.on('will-quit', () => { console.log('Will quit...'); });
app.on('quit', (event, exitCode) => {
console.log(`Application has quit with code: ${exitCode}`);
// This is the very last event.
});Lifecycle Event Check
You've learned about several key Electron application lifecycle events. Now, let's test your understanding!
Lifecycle Events: Key Takeaways
Great job! You've learned how to manage your Electron application's lifecycle, ensuring it starts, runs, and quits gracefully on different operating systems.
- The
appmodule is central to event handling. readyis crucial for initialization and window creation.window-all-closedandactivatehandle window behavior across platforms.will-quitandquitmanage the final stages of app termination.
Mastering these events is fundamental for building robust Electron applications. Keep practicing!
AI 튜터와 함께 JavaScript을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 47
자주 묻는 질문
“앱 수명 주기 이벤트 관리” 강의는 무료인가요?
네 — “앱 수명 주기 이벤트 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Electron Desktop App Development 강의 전체를 잠금 해제할 수 있습니다. Electron Desktop App Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“앱 수명 주기 이벤트 관리”에서 뭘 배우나요?
애플리케이션이 올바르게 동작하도록 `ready`, `window-all-closed`, `activate`, `quit` 등의 다양한 애플리케이션 수명 주기 이벤트를 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 Electron Desktop App Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Electron Desktop App Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Electron Desktop App Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“앱 수명 주기 이벤트 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Electron Desktop App Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Electron Desktop App Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 앱 수명 주기 이벤트 관리
- 자동 업데이트 구현
- 충돌 보고
- 딥 링크와 프로토콜 처리기