关注点分离

昨天在写popover组件的时候方方老师提出了写页面的两个基本原则。

  1. 关注点分离原则,也叫正交原则,HTML CSS JS 分离 互不影响
  2. 状态转移:js不去修改css 的样式(.style.color='red'),只修改css中的状态(addClass('active'))。

1. 关注点分离

页面原则标签、样式、行为三者分离,如下

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body{ /* something */ } </style> </head> <body> <div class="box"> <div class="wrap"> <button class="button">点我</button> <div class="popover active"> <h2>WebUI Popover</h2> <hr> <p> This is webui popover demo. just enjoy it and have fun ! </p> </div> </div> </div> <script> // do something </script> </body> </html> 

像这样,html,css,js全部在一个页面中,如果需要改动,将会变得很麻烦,随着代码量的增加,页面也会变得杂乱,后期难以维护。

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="box"> <div class="wrap"> <button class="button">点我</button> <div class="popover active"> <h2>WebUI Popover</h2> <hr> <p> This is webui popover demo. just enjoy it and have fun ! </p> </div> </div> </div> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="script.js"></script> </body> </html> 

将CSS,JavaScript “剥离”页面,作为链接引入,这样三者之间相互独立,HTML专注于页面结构,CSS专注页面样式,JavaScript 专注页面行为,各司其职,这样虽看起来互不影响,却相互制约,同时页面也变得更加清晰。

“虽然我们并未在一起,但一个src/link就可以把我们紧密相连”

2. 状态转移

除了以上的关注点分离原则以外,还有一个非常重要的原则,即状态转移,如下

$('.button').on('click',function(e){ let $button = $(e.currentTarget) if($('.popover').hasClass('active')){ $('.popover').css('display','none') // not good }else{ $('.popover').css('display','block') } }) $('.button').on('click',function(e){ let $button = $(e.currentTarget) if($('.popover').hasClass('active')){ $('.popover').removeClass('active') // good }else{ $('.popover').addClass('active') } }) 

我们可以认为JavaScript 负责的内容是页面样式的状态的改变,而不去直接改变页面的样式,页面的状态我们可以给某些元素移除/添加某些类间接改变其样式(也可以有其他的做法,但我们不推荐之间改变其CSS样式),这种做法也间接体现了关注点分离的原则,因此状态转移也可以认为是关注点分离中的一种,目的都是为了更好的体现三者之间的关系。



作者:plainnany
链接:https://www.jianshu.com/p/915d4dede919
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自www.cnblogs.com/softidea/p/9696469.html
今日推荐