为什么在控制器中操作 DOM 被认为是一个坏主意? [英] Why is it considered a bad idea to manipulate DOM in controllers?

查看:27
本文介绍了为什么在控制器中操作 DOM 被认为是一个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多人告诉我在控制器中操作DOM是一件很糟糕的事情,但究竟是什么原因.它如何影响您正在制作的应用程序?这样做的最佳做法是什么?是如何做到的?

Many People have told me that it is a very bad thing to manipulate DOM in controllers, but what exactly is the reason. How does it affect the application that you are making? What are the Best Practices to do that and how is it done?

推荐答案

技术上控制器应该更小&紧凑,不应该玩 DOM.控制器只对拥有业务逻辑感兴趣在事件上调用的绑定级别逻辑.

Technically controller should be smaller & compact, it should not be playing with a DOM. Controller will only interested to have a business logic & binding level logic that are being called on events.

在我看来,你不应该从控制器操作 DOM"背后的原因是,这只是因为关注点分离.如果您从控制器进行 DOM 操作,那么它会与您的控制器紧密耦合,&这段代码不能重用.因此,通过在指令中编写该代码,相同的代码可以很容易地变成可插入的 &可重用的组件.只需放置指令标签/元素,您就可以在其他地方使用相同的 DOM 操作.

As per my perspective the reason behind "You should not manipulate DOM from the controller" is, It's just because of separation of concern. If you do the DOM manipulation from the controller then it gets tightly coupled to your controller, & that piece of code can't become reusable. So by writing that code in directive, the same code could be easily become a plug-able & reusable component. You can use the same DOM manipulation elsewhere just by putting directive tag/element.

查看指令定义,然后你会分析它只是为了玩 DOM,因为它在使用 preLInk 函数渲染它之前给了一个控制器来控制 DOM.也可以在 postLink 函数中获得 DOM 的后期渲染.

Looked at directive definition, then you will analysed that it just meant to play with DOM, as it give a controller over DOM before rendering it using preLInk function & also post rendering of DOM you can get in postLink function.

还有指令使您可以使用指令元素,您无需编译它,因为该 element 已经用 jQLite 编译,这是 angular 中使用的 jQuery 的较小版本.这里不需要选择器来获取指令元素 DOM.

Also directive make you available the directive element, you no need to make it compile because that element has already compiled with jQLite which is smaller version of jQuery used in angular. No need of selector here to get directive element DOM.

这篇关于为什么在控制器中操作 DOM 被认为是一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆