AngularJS 中的大量属性是否表明存在问题?

Is a large number of attributes in AngularJS indicative of an issue?

一个普遍的共识是,除非有充分的理由不这样做,否则方法的参数数量应该足够小

多少 足够小 因作者而异(史蒂夫·麦康奈尔在 代码完成 中有七个,罗伯特·C·马丁有三个清洁代码);我想大多数开发人员都会同意,如果 class 中的大多数方法包含五个或更多参数,或者如果给定方法包含十个以上参数,则需要进一步调查。

此准则是否适用于 AngularJS 属性?通过属性,我的意思是 hellosomething in:

<my-component hello="world" something="abc" ...></my-component>

一个实际案例是我正在审查一个项目,其中有一堆 AngularJS 组件和指令,其中包含八到十个属性,有些包含多达十五个。如果这些是方法,我会发出警报。但是,我不确定 AngularJS 的特殊性,这可以证明具有非常扁平的结构而不是将属于一起的属性分组到单独的对象中。

我想对属性进行分组的原因之一是能够以更细粒度的方式定义属性样式(单向等)。

我想说的是,属性需要从视图传递到组件的方式不应该有任何限制 class。

我们应该称之为绑定到属性吗

我会说你应该将此属性称为 html 语法,我们通过将特殊变量绑定到此属性来将数据传递给组件 class。

此外,这些属性值不是作为函数参数传递的,而是 class 中的变量。

html 属性

HTML 属性不能限制为 5 或 10。您可以在 UI 中根据您的要求提供属性数量。有人说 angular 组件是新标签 ang html 6 什么的

angular[2/4]

的例子

这里我通过添加两个属性向我的子组件传递了 2 个值

如果你愿意,我应该允许我绑定多少个我想绑定多少个

在我的 class 中,我只有变量来处理它。

export class EditComponent implements OnInit {

  @Input() text: string;
  @Output() editDone = new EventEmitter<Object>();
  private originalText: string;

希望对您有所帮助。

鉴于 html 对属性没有限制,angularjs 对绑定也没有限制,这不会因为绑定的数量而成为问题。

但是,这至少在设计方面可能是个问题,这取决于每种情况。也许你在谈论一个 Dumb Component,比如说 ui-gmap-google-map directive 它可能有很多绑定,例如:

<ui-gmap-google-map
    center="map.center"
    zoom="map.zoom"
    dragging="map.dragging"
    bounds="map.bounds"
    events="map.events"
    options="map.options"
    pan="true"
    control="map.control">
</ui-gmap-google-map>

在这种情况下,使用这种方法是完全可以接受的并且是正常的,即使它有替代方案,例如子组件和嵌入区域。

但是,如果您谈论的是 智能组件,比如页面组件指令,上面有太多绑定,看起来组件不是那么智能并且依赖绑定太多无法生存。

Note on Bindings: As per you've exemplified the function arguments case, for the bindings applies the same rule, to keep the function more responsible and as pure you can make it. Components on the other hand is required to have it's responsibilities solid and single, so the bindings are the arguments it require to do its responsibility.

Therefore, a large amount of bindings (or arguments) can be a sign of a not so responsible component, but it's not the binding number that is the issue, is the garbage designed component;