AngularJs 1.5 - 基于组件的架构、绑定和良好实践

AngularJs 1.5 - Component Based Architecture, Bindings and Good Practices

按照我的问题

我有一些关于基于组件的架构的额外设计问题。

1- 根据 Gui 的描述,如果我有一个 child 组件绑定了 parent,我应该处理 parent 上的数据操作。那么,我是将数据保存在 parent 还是 child 中?

示例

 <my-child on-save="$ctrl.save"></my-child>

MyChild 组件包含一个用于保存数据的表单。 在这种情况下,我应该在哪里保存数据,在 parent 或 child 中?假设我在 child 中执行此操作,我使用 parent 保存功能来更新 UI ?

2- 如果我有一个没有绑定的 child 组件,在 child 中进行数据保存和操作是否正确?

3- 理想情况下,所有应用程序都应该是一个组件树。假设我有一个名为 using ng-view 和 router 的表单。一般来说,我必须考虑一个核心或 parent 组件,代表整个应用程序 ui,例如,我的表单是 child ?所以我必须像第 1 点和第 2 点那样传播绑定?

希望我的问题很清楚

为了解释这一点,我首先必须考虑一些可能会改变您对应用程序设计的看法的组件。

组件

组件是对既是整体的一部分又是由另一个整体组成的事物的通用定义,但它并没有具体说明每个组件在整体中的作用。因此,在基于组件的体系结构中,通常会定义指令来以一种可以更好地定义每个角色的方式处理组件。

例如:一堆组件,一个由另一个组成,但所有组件;

<component>    
    <component></component>
    <component>        
        <component></component>
        <component></component>        
    </component>    
</component>

聪明和笨拙的组件

我了解到大多数基于组件的框架和库都使用这种方法。组件分为两类,智能组件和哑组件。 Tero Parviainen's article and also by Dan Abramov.

更好地描述了这一点

例如:still,都是组件,但是由其类别定义

<app>
    <nav></nav>
    <!-- projects-page is Dumb: I don't have to know nothing
    <!-- just organize and display things -->
    <projects-page>
        <!-- project-list is Smart: I must know how to retrieve projects -->
        <project-list>
            <!-- Dumb: just display -->
            <project-list-item></project-list-item>
            <!-- Dumb: just display -->     
            <project-list-item></project-list-item>
        </project-list>
    </projects-page>    
</app>

基本上,Smart 组件连接到应用程序逻辑,它们知道工作原理。尽管他们可能有输入和输出,但他们大多知道如何加载自己的数据,以及如何在发生变化时保持变化。但是 Dumb 组件只知道事物应该是什么样子,并且完全由它们的绑定定义:它们使用的所有数据都作为输入提供给它们,它们引入的每一个变化都会作为输出出现, Toward Smart And Dumb Components, Tero Parviainen's.

回答

所以你的问题的答案是:这取决于你如何看待子表单组件,它是否只是一个显示字段的编辑器(即,愚蠢,我认为在这种情况下是这样)。或者负责通过检索和命令与持久性单元的通信来保存它(即智能)。

无论如何,最重要的是确保您从智能组件保存数据,最好是从该数据的所有者那里保存数据。将智能组件视为管理者,将愚蠢组件视为生产者。另外,查看这篇关于编写基于组件的应用程序的文章:Writing component based goats dating app with angular 1.5 由 Dima Grossman 撰写。

NOTE: Think about smart components as stateful. It basically means that smart components are less reusable in some cases. If you have to reuse the form-component on another component where the object project is a part of another object (e.g., { client: { name: '', projects: [{ id:1, ...} ...]) and you want to use the same form to edit the project within this object you'll face an issue. You can't reuse the exact same component logic, therefore in this situation a dumb component can be more useful for reusing, because it's more simple and objective with a proceeding and it doesn't take any decision, just show things, receive and return data.