|
463 | 463 | const view = new View(doc.querySelector('#mvp-dispatch-view'))
|
464 | 464 | const controller = new Controller(view, model)
|
465 | 465 | controller.init()
|
466 |
| - })(window, document) !(function(win, doc) { |
467 |
| - class Observer { |
468 |
| - constructor() { |
469 |
| - this.observers = [] |
470 |
| - } |
471 |
| - register(callback) { |
472 |
| - this.observers.push(callback) |
473 |
| - } |
474 |
| - notify(args) { |
475 |
| - for (let i = 0, l = this.observers.length; i < l; i++) { |
476 |
| - this.observers[i](args) |
477 |
| - } |
478 |
| - } |
479 |
| - } |
480 |
| - // View |
481 |
| - class View { |
482 |
| - constructor($el, tpl) { |
483 |
| - this.$el = $el |
484 |
| - this.tpl = tpl |
485 |
| - this.onAdd = new Observer(this) |
486 |
| - this.onChange = new Observer(this) |
487 |
| - } |
488 |
| - render(data) { |
489 |
| - this.$el.innerHTML = this.compile(data) |
490 |
| - } |
491 |
| - compile(data) { |
492 |
| - return this.tpl || `<div><b>${data.name}</b> |
493 |
| - <em>${data.num}</em></div>` |
494 |
| - } |
495 |
| - } |
496 |
| - // Model |
497 |
| - class Model { |
498 |
| - constructor() { |
499 |
| - this.data = { name: 'MVP+Dispatch', num: 1 } |
500 |
| - this.onUpdate = new Observer(this) |
501 |
| - this.onChange = new Observer(this) |
502 |
| - } |
503 |
| - update(value) { |
504 |
| - const fn = (res) => { |
505 |
| - this.data.num += value |
506 |
| - this.onUpdate.notify(value) |
507 |
| - } |
508 |
| - fetch('./').then(fn).catch(fn) |
509 |
| - } |
510 |
| - change(name) { |
511 |
| - this.data.name = name |
512 |
| - this.onChange.notify(name) |
513 |
| - } |
514 |
| - } |
515 |
| - // Controller |
516 |
| - class Controller { |
517 |
| - constructor(view, model) { |
518 |
| - this.view = view |
519 |
| - this.model = model |
520 |
| - } |
521 |
| - init() { |
522 |
| - this.view.$el.addEventListener('click', evt => this.view.onAdd.notify(1)) |
523 |
| - this.view.$el.addEventListener('mouseout', evt => this.view.onChange.notify('Click to add')) |
524 |
| - this.view.onAdd.register(value => { |
525 |
| - this.model.data.name = 'Click to add:Event dispatch.' |
526 |
| - this.model.update(value) |
527 |
| - }) |
528 |
| - this.view.onChange.register(name => this.model.change(name)) |
529 |
| - this.model.onUpdate.register(value => this.view.render(this.model.data)) |
530 |
| - this.model.onChange.register(name => this.view.render(this.model.data)) |
531 |
| - this.view.render(this.model.data) |
532 |
| - } |
533 |
| - } |
534 |
| - const model = new Model() |
535 |
| - const view = new View(doc.querySelector('#mvp-dispatch-view')) |
536 |
| - const controller = new Controller(view, model) |
537 |
| - controller.init() |
538 |
| - })(window, document)v |
| 466 | + }) |
539 | 467 | ```
|
540 | 468 |
|
541 | 469 | ### 6. 前端MVVM模式,通过观察者模式将数据与视图进行双向绑定,然后由数据驱动更改
|
|
0 commit comments