웹 프론트엔드 JS 튜토리얼 Oats~i로 웹 앱 구축 – Oats~i 앱 시작하기

Oats~i로 웹 앱 구축 – Oats~i 앱 시작하기

Aug 21, 2024 am 06:05 AM

Oats~i 튜토리얼 시리즈의 두 번째 부분에 오신 것을 환영합니다. 첫 번째 부분에서는 개발 환경에 Oats~i를 설치하는 과정을 진행했습니다. 혹시 놓치셨다면 여기에서 확인해 보세요.

이번 시리즈에서는 Oats~i 앱을 시작하는 방법을 살펴보겠습니다. 이는 Oats~i 앱을 시작하고 프런트 엔드에서 프레임워크를 실행하려는 모든 경우를 다룹니다.

전체 프로젝트를 처음부터 구축하는 대신 Oats~i CLI를 사용하여 Oats~i를 설정할 때 Oats~i와 함께 제공되는 내장 시작 프로젝트를 사용하겠습니다. 이 튜토리얼에 필요한 코드의 중요한 부분을 열고 이를 사용하여 Oats~i가 클라이언트/브라우저에 도달하고 웹 앱 실행을 시작할 때 어떻게 로드되는지 설명하겠습니다.

자세히 살펴보겠습니다.

Oats~i CLI를 사용하여 스타터 프로젝트 설치

Oats~i 스타터 프로젝트를 설치할 새 폴더를 만들고 터미널을 엽니다. 그런 다음 다음을 실행하세요.

npx oats-i-cli

로그인 후 복사

안내를 따르세요.

이렇게 하면 Oats~i와 함께 제공되는 시작 프로젝트가 현재 작업 디렉터리에 설치됩니다.

마지막으로 시작 프로젝트를 실행하려면

npm run dev

로그인 후 복사

터미널에 제공된 주소(종종 localhost:8080)로 이동하여 시작 프로젝트가 실행되는 모습을 확인하세요. 사용 가능한 페이지 사이를 오가며 Oats~i가 라우팅을 처리하고 프래그먼트를 통해 뷰를 빌드하는 것을 확인하세요.

이제 클라이언트/브라우저에서 Oats~i를 생생하게 구현하는 코드를 살펴보겠습니다.

Index.js

src에 있는 index.js 파일을 엽니다. -> 앱 -> 인덱스 -> 스크립트.

Build a Web App with Oats~i – Starting an Oats~i App

이 파일에는 cli에 번들로 포함된 시작 프로젝트용 Oats~i를 시작하는 코드가 포함되어 있습니다. 이는 자신의 프로젝트에서 Oats~i를 시작하기 위해 작성하는 코드와 거의 동일합니다.

분해해 보겠습니다.

앱 루트

Oats~i는 일반적으로 appRoot.initApp() 메서드를 통해 appRoot 모듈에서 초기화됩니다.

appRoot는 Oats~i 웹 앱의 초기화, 기본 탐색, 템플릿이 제공되는 경우 루트 보기 로드를 관리하는 AppRoot 클래스의 싱글톤 인스턴스입니다.

initApp() 메서드는 AppStateManager, MainRouter, AppRootView 개체의 인스턴스, 기본 경로, 현재 앱의 외부 링크 차단 동작을 정의할 수 있는 선택적 추가 옵션을 비롯한 여러 인수를 사용합니다.

이를 분석해 보겠습니다.

앱상태관리자

앱 상태 관리자는 Oats~i 앱의 경로 상태를 관리하는 모듈입니다. 주로 Oats~i가 히스토리 팝 이벤트가 사용자가 브라우저에서 앞으로 또는 뒤로 버튼을 클릭한 것인지 이해하는 데 도움이 됩니다.

이 정보는 히스토리 API를 그대로 사용하면 명확하지 않습니다.

Oats~i는 사용자가 웹 앱을 탐색할 때 조각 상태를 저장하기 때문에 이 정보를 갖는 것이 중요합니다. 따라서 이전에 있었던 페이지로 돌아가거나 앞으로 이동하려는 경우 해당 페이지의 렌더링 및 실행을 담당하는 조각은 해당 상태를 "기억"하고 올바른 정보를 표시하며 자동으로 올바른 위치로 스크롤됩니다. 사용자는

에 있었습니다.

팝 이벤트가 전진인지 후진인지 알면 상태 정보를 정확하게 검색할 수 있습니다.

새 앱을 호출하고 웹 앱의 라우팅 정보를 전달하여 AppStateManager의 인스턴스를 생성하기만 하면 됩니다.

index.js 파일에서는 다음 줄에서 이 작업을 수행합니다.

const appStateManager = new AppStateManager(AppRoutingInfo);

로그인 후 복사

이미 AppRoutingInfo를 별도의 파일에 정의했습니다(나중에 자세히 설명).

메인 라우터

메인 라우터는 Oats~i 웹 앱에서 라우팅을 처리합니다. "new"를 호출하고 앱의 라우팅 정보, 앱 상태 관리자 인스턴스, 오류 콜백, 루트 경로 및 경로 동의 콜백을 전달하여 라우터 인스턴스를 생성합니다.

앱 라우팅 정보와 앱 상태 관리자 인스턴스에 대해서는 이미 이야기했으므로 기본 라우터에 전달하는 다른 인수에 대해 이야기해 보겠습니다.

오류 콜백

라우팅에 문제가 있는 경우 기본 라우터는 오류 콜백을 실행하고 라우팅이 실패한 이유를 알려줄 수 있습니다. 경로를 잘 정의했다면 이 방법을 단순히 제공하는 것 외에는 구현에 대해 걱정하지 않아도 됩니다.

루트 경로

메인 라우터에서는 RouteTO() 메소드를 사용하여 JavaScript 코드에서 라우팅을 직접 호출할 수 있습니다. 또한 앱의 기본 경로 정보를 기반으로 따라야 할 유효한 경로를 결정합니다.

Now, if you have Oats~i running in your website with a special address such as /admin, it can be repetitive having to start every routing call or routing info with the /admin root. Instead, you can supply this to the main router as the root path, and just append the rest of your route to your routing calls or routing info.

So, instead of /admin/create, with the root path set to /admin, you can just have the route as /create. However, href attributes in links MUST be fully qualified.

Route Consent Callback

Before the main router can trigger routing for a given path, it attempts to see whether routing for that route has been permitted. The route consent callback allows you to specify this, giving you the ability to control which sections of your web app can be accessed by a given user or based on any other business or app logic.

Note: This is different from fragment consenting, which we’ll cover later.

AppRootView Object

The app root view object consists of the root view template and array of main navigation infos.

Every Oats~i app has a root view. This is the permanent section of the view which the user will always see regardless of the path they’re navigating to. The root view is wrapped within an tag and will typically contain elements such as your navbar and footer.

Here’s an example, sourced from home.sv.hbs in the Oats~i starter project

<app-root id="my-app">
        <div id="nav">
            <a href="/" class="nav-link open-sans-txt home-link"><span></span><span>Home</span></a>
            <a href="/about" class="nav-link open-sans-txt about-link"><span></span><span>About</span></a>
        </div>
        <div id="site-bg"></div>
        <main-fragment>

        </main-fragment>
</app-root>
로그인 후 복사

Note: As you can infer from the Oats~i starter project, you can skip passing in a template for the app root view in the initApp() method as long as you’ve provided it in the html markup sourced for your page from the server.

Your root view object should also have a single tag specified within, where the app’s fragments will be loaded.

The AppRootView object also takes a main navigation info array, which contains a list of selectors and their active routes, which Oats~i will use to show you which navigation selector is active.

In the Oats~i starter project, specifying the main nav info makes it possible to update the styling and looks of the navigation links when you click on it and navigate to its url.

Oats~i handles the click and update boiler plate for the navigation links or buttons. All you have to do is style the links or buttons based on which one is marked as active using the attribute ‘navigation-state=”active”’

Default Route

The default route is the route Oats~i will default to incase the page loads from a url that is not specified in your app’s routing info. You can use this to curate the default web app behavior especially if it results from a log in or authentication action.

For instance, if the user has come in from a login page and is redirected to their admin page, but the initial page load is at “/admin”, you can specify the default route to be “/admin/dashboard”.

Oats~i will reroute the web app to /admin/dashboard on load and the user will always access their dashboard every time they come from logging into the app.

If you want to change this behavior to say, profile, you can simply change the default route in your web app to /admin/profile and all users logging in will have their profile page as the default page.

Extra Options

Oats~i also takes in optional extra options, with the current implementation allowing you to intercept external links within your web app. This allows you to warn users of their navigation away from your site and the url they’re about to access, in case you want to build a content protection system.

Complete Code

The complete code for starting an Oats~i app will look something like this:

//sourced from index.js in the starter app
const appStateManager = new AppStateManager(AppRoutingInfo);
    appRoot.initApp(appStateManager, new MainRouter(AppRoutingInfo, appStateManager, (args) => {}, "", async (url) => {

        return {

            canAccess: true,
            fallbackRoute: "/"
        }
    }), { template: null, mainNavInfos: AppMainNavInfo }, "");

로그인 후 복사

You can wrap this code within a function that is automatically invoked when your index.js file downloads in the browser to have the web app automatically started on page load. In the starter project’s case, this is the initApp() function.

Now, there are two more things left to explain.

App Routing Info

From the startup code, you can point out that providing routing information is mandatory for an Oats~i web app to initialize. From the example’s I’ve given, we define this info elsewhere then import it in our startup script. Defining your routing info in a separate file is not mandatory, but I find it to be good practice especially when you want to add more routes or main navigation in your web app.

Here’s how routing information is defined for an Oats~i web app, using the example from the starter project.

const AppRoutingInfo = RoutingInfoUtils.buildMainRoutingInfo([

    {
        route: "/",
        target: homeMainFragmentBuilder,
        nestedChildFragments: null
    },
    {
        route: "/about",
        target: aboutMainFragmentBuilder,
        nestedChildFragments: null
    }
], AppMainNavInfo);

로그인 후 복사

You can call the routing info any name you want, as long as you use the method RoutingInfoUtils.buildMainRoutingInfo() to build it.

The method will return an array of routing information, with each info holding:

  • route: this is the route that info is valid for. You cannot repeat a route across your routing infos.
  • target: this is the main fragment the route should start building from. Oats~i builds its fragments from the main fragment to the child fragments
  • Nested child fragments: these are the child fragments that should also be built for the route, in order. This order typically represents the DOM structure, with the fragment that should be created first in DOM coming before it’s nested child or a child fragment in the same level with it.

You can notice that we also pass AppMainNavInfo to the buildMainRoutingInfo() method as well. This is the same info we passed in to the app state manager and initApp method in the starter script. Let’s look at it.

App Main Nav Info

A good web app needs good navigation. And often, setting up navigation can involve a lot of boiler plate code to not only set up the click listeners for the navigation links or buttons, but also change their styling based on which one is active.

Oats~i takes care of the boiler plate for you by requiring you only provide the navigation information needed by your web app. This takes the following format (example sourced from the starter project).

const AppMainNavInfo = MainNavigationInfoBuilder.buildMainNavigationInfo([

    {
        selector: "home-link",
        defaultRoute: "/",
        baseActiveRoute: "/",
    },
    {
        selector: "about-link",
        defaultRoute: "/about",
        baseActiveRoute: "/about",
    }
]);

로그인 후 복사

You create a main navigation info in Oats~i using the method MainNavigationInfoBuilder.buildMainNavigationInfo(). It returns an array of navigation infos, with each containing:

  • selector: This is a dot selector that Oats~i will use to query the navigation link or button, set up listeners (for buttons only – links/A tags are automatically intercepted), and update its “navigation-state” attribute based on whether its active or not. In your markup, this is simply a class name.
  • defaultRoute: this is the default route Oats~i should route to if the navigation button is clicked. For links, since Oats~i automatically intercepts clicks on links/A tags, ensure this matches the value of your href attribute.
  • baseActiveRoute: This is the base route for which the navigation button or link should be treated as active. For instance, if you have a navigation button with defaultRoute “/profile” and baseActiveRoute “/profile” and the user navigates to /profile/update-pic, Oats~i will set this button as active since this route starts with the baseActiveRoute value.

Putting Everything Together

Let’s put everything together and have the final picture of what you need to get an Oats~i app up and running. Typically, you must have defined:

  • The app routing info
  • The app main nav info (for main navigation links in your root view)

Then, simply get a new instance of the app state manager, and call appRoot.initApp passing this instance, the app routing info, app main nav info, and main router instance. Again, here’s the example code from the Oats~i starter project that comes bundled with the cli, now wrapped in a function that we call immediately the index.js file loads in the browser.

function initApp(){

    const appStateManager = new AppStateManager(AppRoutingInfo);
    appRoot.initApp(appStateManager, new MainRouter(AppRoutingInfo, appStateManager, (args) => {}, "", async (url) => {

        return {

            canAccess: true,
            fallbackRoute: "/"
        }
    }), { template: null, mainNavInfos: AppMainNavInfo }, "");
}

initApp();

로그인 후 복사

As your web app grows and changes, the only bits of this code you’ll ever need to change are the app routing infos and main navigation infos (AppRoutingInfo and AppMainNavInfo). This will be typically because you’re adding new routes to your web app (thus updating the routing information) or adding new main navigation buttons or links (thus updating the main navigation infos).

The rest of the code will be fine untouched.

Sign Up and Follow for the Next Tutorial

A lot of this will make sense when we build our very own small project in Oats~i. That’s what we’ll be doing in the next part of this series, to learn the next fundamental concepts around building an Oats~i web app.

See you then.

Support Oats~i

You can support the development of Oats~i through Patreon or buy me a coffee.

위 내용은 Oats~i로 웹 앱 구축 – Oats~i 앱 시작하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python vs. JavaScript : 학습 곡선 및 사용 편의성 Python vs. JavaScript : 학습 곡선 및 사용 편의성 Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

JavaScript 및 웹 : 핵심 기능 및 사용 사례 JavaScript 및 웹 : 핵심 기능 및 사용 사례 Apr 18, 2025 am 12:19 AM

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

자바 스크립트 행동 : 실제 예제 및 프로젝트 자바 스크립트 행동 : 실제 예제 및 프로젝트 Apr 19, 2025 am 12:13 AM

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

JavaScript 엔진 이해 : 구현 세부 사항 JavaScript 엔진 이해 : 구현 세부 사항 Apr 17, 2025 am 12:05 AM

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스 Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스 Apr 15, 2025 am 12:16 AM

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Python vs. JavaScript : 개발 환경 및 도구 Python vs. JavaScript : 개발 환경 및 도구 Apr 26, 2025 am 12:09 AM

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

JavaScript 통역사 및 컴파일러에서 C/C의 역할 JavaScript 통역사 및 컴파일러에서 C/C의 역할 Apr 20, 2025 am 12:01 AM

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교 Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교 Apr 21, 2025 am 12:01 AM

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.

See all articles