MVC 是什么?(续1)

上期讲了「后端 MVC」,本期讲「前端 MVC」。

前后端分离

前端 MVC 就要从前后端分离讲起了。

前后端分离是指

一个页面分为两部分,浏览器上面的工作交给前端做,服务器上面的工作交给后端做(人员分离)

页面开发流程是这样的

1. 浏览器第一次加载的页面只是一个占位符,比如这样

<body>
  <div id=app></div>
</body>

2. 前端将其他 HTML 和从服务器获取的数据填到占位符里

伪代码:

$.get('/user/1').then(function(user){

  template = (
    <h1>{{ name }}</h1>
  )

  content = template.replace('{{ title }}', user.name)

  $app.html(content)

})

3. 用户提交数据时,前端用 AJAX 提交异步请求

$form.on('submit', function(){
  $.post('/user/1', $form.serialize()).then(function(){
    alert('提交成功')
  })
})

老司机的总结

前端老司机发现自己每个项目都要重复上面的流程,于是也想总结一下,归纳一下,抽象一下。

假设我们要做一个用户中心页面。

Model – 封装数据操作

对用户的增删改成其实都是异步请求,我能不能封装到一起呢?

var userModel = {
  find: function(id){
    return $.get('/user/'+id).then(function(user){
      $.extend(userModel, user)
    })
  },
  save: function(id, data){
    return $.post('/user/'+id, data)
  }
}

出了这些,还有用户数据的校验

userModel.validate = function(){
  if(this.name === '') return false
  if(this.password === '') return false
  return true
}

这样一来,数据相关的操作就都放到这个 model 上了。

View – 视图渲染

前端的视图也是 HTML,由于 HTML 里面没有数据,所以我们一般都要将数据与 HTML 混合起来。

上面代码是这样做混合的:

content = template.replace('{{ title }}', user.name)

显然这样的方案功能不够强大,于是前端们用正则写出很多强大的模板引擎,如 Handlebars.js、React,最终实现的效果大致是:

content = templateEngine( template, user )

content 就是带有数据的 HTML 了。

Controller – 控制器主要是打杂的

还有哪些事情没做,都交给 Controller 吧:

  1. 将 content 塞到页面里
  2. 浏览器事件监听 – 用户点击视图后去更新数据(如 user)
  3. 数据事件监听 – user 数据更新后去更新视图

对应的代码:

controller = {
  model: userModel,
  element: $app,
  template: '<h1>{{ name }} </h1>........',
  events: {
    'click button': 'onButtonClick',
    'submit form' : 'onSubmitForm'
  },
  modelEvents: {
    'update': 'onModelUpdate',
    'remove': 'onModelRemove'
  },
  init: function(){
    var content = templateEngine(this.template, userModel)
    this.element.append($app)

    // 遍历 events 并绑定对应的方法
    // 遍历 modelEvents 并绑定对应的方法
  },
  onButtonClick: function(){...},
  onSubmitForm: function(){...},
  onModelUpdate: function(){...},
  onModelRemove: function(){...}
}

总结一下:

  1. Controller 监听 Model 变化,Model 一变,Controller 就会去更新 View。
  2. Controller 监听用户交互,用户点了提交或修改按钮,Controller 就要去更新 Model。

注意,一个页面可以有多个 Controller,每个 Controller 负责一个大 div 即可。

Router – 路由

前端 MVC 有路由吗?可以有,也可以没有。

如果只是在每个页面局部使用 MVC,那么就不需要路由。

如果整站是一个单页面,那么就要处理 URL 的变化了(用 PushState API 或者 URL Hash)。

MVC 里面最复杂的部分是 Controller,它做了太多机械的、繁琐的事情,比如绑定事件、更新 DOM、更新数据,这也为前端 MVC 没落留下了隐患,后面的 MVP、MVVM、FLUX 很好地解决这一问题(同时引入了其他问题)。不过 MVC 的概念,我们还是有必要了解的。

作者:方应杭

130 thoughts on “MVC 是什么?(续1)”

  1. Very good website you have here but I was wanting to know if you knew of any discussion boards that cover the same topics talked about in this article? I’d really love to be a part of online community where I can get responses from other experienced individuals that share the same interest. If you have any recommendations, please let me know. Kudos!|

  2. Its like you learn my thoughts! You seem to understand so much approximately this, such as you wrote the book in it or something. I believe that you just could do with a few p.c. to force the message house a little bit, however other than that, this is great blog. A great read. I’ll definitely be back.|

  3. I feel this is among the most vital information for me. And i’m satisfied studying your article. But want to statement on few general things, The website style is wonderful, the articles is truly nice : D. Just right activity, cheers|

  4. This is a very good tip particularly to those fresh to the blogosphere. Simple but very precise information… Thanks for sharing this one. A must read post!|

  5. Good day! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Thanks!|

  6. You actually make it seem so easy with your presentation however I in finding this matter to be actually something which I believe I might by no means understand. It sort of feels too complex and extremely large for me. I am taking a look ahead on your next submit, I’ll try to get the hold of it!|

  7. After exploring a handful of the blog articles on your site, I really appreciate your technique of blogging. I saved as a favorite it to my bookmark site list and will be checking back in the near future. Take a look at my web site as well and tell me what you think.|

  8. I’m more than happy to discover this great site. I wanted to thank you for your time due to this wonderful read!! I definitely appreciated every part of it and I have you book-marked to check out new stuff in your site.|

  9. I truly love your site.. Very nice colors & theme.
    Did you create this web site yourself? Please reply back as I’m
    wanting to create my very own site and would love to know where you got this from or what the theme is named.
    Thanks!

  10. I think this is one of the most significant information for me. And i am glad reading your article. But want to remark on few general things, The site style is ideal, the articles is really nice : D. Good job, cheers|

  11. We are a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable information to work on. You have done a formidable job and our whole community will be grateful to you.|

  12. I love reading through an article that will make people think.

    Also, many thanks for permitting me to comment!

  13. Hey there! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about making my own but I’m not sure where to start. Do you have any ideas or suggestions? Many thanks|

  14. When someone writes an piece of writing he/she maintains the thought of a user in his/her mind that how a user can be aware of it. So that’s why this paragraph is amazing. Thanks!|

  15. Hey there, You have done a fantastic job. I’ll definitely digg it and individually recommend to my friends. I am confident they will be benefited from this site.|

  16. Wonderful goods from you, man. I’ve understand your stuff previous to and you are just extremely excellent. I really like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can not wait to read much more from you. This is actually a wonderful website.|

  17. Hi i am kavin, its my first occasion to commenting anyplace, when i read this post i thought i could also make comment due to this good piece of writing.|

  18. Hi are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and create my own.
    Do you need any html coding expertise to make your own blog?
    Any help would be really appreciated!

  19. Magnificent goods from you, man. I’ve understand your stuff previous to and you are just too wonderful. I actually like what you’ve acquired here, really like what you are stating and the way in which you say it. You make it entertaining and you still care for to keep it smart. I cant wait to read much more from you. This is actually a wonderful site.|

  20. I need to to thank you for this very good read!! I absolutely enjoyed every little bit of it. I’ve got you book marked to look at new stuff you post…|

  21. An impressive share! I’ve just forwarded this onto a coworker who was doing a little homework on this. And he in fact bought me dinner due to the fact that I discovered it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to discuss this issue here on your blog.|

  22. Definitely imagine that which you said. Your favourite justification seemed to be on the web the easiest factor to be aware of. I say to you, I definitely get irked whilst other people think about concerns that they plainly don’t understand about. You managed to hit the nail upon the top as smartly as defined out the entire thing with no need side effect , people could take a signal. Will likely be again to get more. Thanks|

  23. It is in reality a great and useful piece of information. I am glad that you shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.|

  24. It is appropriate time to make a few plans for the future and it is time to be happy. I’ve learn this publish and if I could I want to suggest you few attention-grabbing things or suggestions. Maybe you can write next articles relating to this article. I want to read even more issues approximately it!|

  25. Whats up this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!|

  26. Howdy, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you protect against it, any plugin or anything you can suggest? I get so much lately it’s driving me mad so any assistance is very much appreciated.|

  27. Howdy would you mind letting me know which hosting company you’re utilizing? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at a honest price? Thanks, I appreciate it!|

  28. First off I would like to say terrific blog! I had a quick question in which I’d like to ask if you do not mind. I was interested to know how you center yourself and clear your thoughts before writing. I have had difficulty clearing my thoughts in getting my thoughts out there. I truly do enjoy writing however it just seems like the first 10 to 15 minutes are usually lost just trying to figure out how to begin. Any suggestions or tips? Thanks!|

  29. Hi there just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design look great though! Hope you get the problem fixed soon. Cheers|

  30. You actually make it appear so easy together with your presentation but I find this matter to be actually something which I feel I’d never understand. It sort of feels too complex and very large for me. I’m looking ahead in your subsequent publish, I’ll try to get the hold of it!|

  31. You’re so interesting! I do not think I’ve truly read through something like that before. So nice to find somebody with some original thoughts on this subject. Seriously.. thank you for starting this up. This website is something that’s needed on the web, someone with a bit of originality!|

  32. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is fundamental and all. Nevertheless think of if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could undeniably be one of the greatest in its field. Awesome blog!|

  33. I have been browsing online more than 2 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the net will be a lot more useful than ever before.|

  34. Does your website have a contact page? I’m having a tough time locating it but, I’d like to shoot you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it expand over time.|

  35. I just like the valuable information you supply in your articles. I’ll bookmark your weblog and check again right here frequently. I’m somewhat sure I’ll learn many new stuff proper here! Good luck for the next!|

  36. It’s perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or suggestions. Maybe you can write next articles referring to this article. I desire to read more things about it!|

  37. I don’t even know how I ended up here, but I thought this post was great. I don’t know who you are but definitely you’re going to a famous blogger if you are not already 😉 Cheers!|

  38. Its like you learn my mind! You appear to know so much approximately this, such as you wrote the e book in it or something. I believe that you just can do with a few p.c. to force the message house a little bit, however instead of that, that is great blog. A great read. I will certainly be back.|

  39. Hi! Someone in my Myspace group shared this website with us so I came to take a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Excellent blog and fantastic design and style.|

  40. Hello There. I found your blog the use of
    msn. This is a really well written article. I’ll make sure to bookmark it
    and come back to read extra of your useful
    information. Thanks for the post. I will definitely return.

  41. Ahaa, its nice dialogue about this post here at this webpage, I have read all that, so at this time me also commenting here.|

  42. Awesome blog! Do you have any hints for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any ideas? Bless you!|

  43. I have been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the net will be much more useful than ever before.|

  44. As predicted all space coffins and space funeral homes will blow up in space around the year 2080 to year 3000 due to envy. That’s why we need the 777 immortality smart contracts to remind the living to have faith through time. The 777 immortality smart contract is the trust system that can save someone you love through time.

  45. Hey there! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Superb blog and superb design and style.|

  46. Hi, I do believe this is an excellent blog. I stumbledupon it 😉 I will revisit yet again since i have book marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.|

  47. Does your website have a contact page? I’m having trouble locating it but, I’d like to send you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.|

  48. Its like you read my thoughts! You appear to grasp so much about this, like you wrote the ebook in it or something. I feel that you could do with some percent to power the message home a bit, but other than that, this is excellent blog. An excellent read. I will certainly be back.|

  49. Hi, Neat post. There is an issue with your web site in internet
    explorer, might check this? IE still is the marketplace
    chief and a huge element of other people will leave out your great writing because of this problem.

  50. I’m really loving the theme/design of your website. Do you ever run into any web browser compatibility problems? A small number of my blog visitors have complained about my site not working correctly in Explorer but looks great in Safari. Do you have any suggestions to help fix this issue?|

  51. I’m amazed, I have to admit. Rarely do I come
    across a blog that’s equally educative and entertaining, and let me tell you,
    you have hit the nail on the head. The problem is an issue that not enough
    people are speaking intelligently about. I am very happy I came across this in my search for something concerning
    this.

  52. Its like you learn my mind! You seem to know a lot approximately this, such as you wrote the ebook in it or something. I believe that you could do with a few to pressure the message home a bit, however instead of that, this is fantastic blog. An excellent read. I’ll definitely be back.|

  53. Hi there, simply became aware of your weblog thru Google, and found that it’s really informative. I’m gonna watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited out of your writing. Cheers!|

  54. Thanks for the marvelous posting! I genuinely enjoyed reading it, you can be a great author.

    I will be sure to bookmark your blog and will come back down the road.

    I want to encourage you to definitely continue your great posts, have a nice weekend!

发表评论

电子邮件地址不会被公开。