繁体   English   中英

MVC 交叉点观察者结构

[英]MVC Intersection Observer structure

我想知道是否有人可以帮助我处理 MVC 架构。 我从 Udemy 上了一门 MVC 课程,现在我有一个我正在从事的宠物项目。 简而言之。 我有三个 JS 文件:controller、model 和视图。

我正在观看 activeHeading2 元素,用户滚动它,操作两个元素上的类。 无论如何,现在发生的事情是当用户单击并显示带有新的 activeHeading2 元素的新部分时,即使我告诉它不观察甚至断开连接,Observer 仍然会在视图中观察旧部分 activeHeading2。 我已经坚持了一周,任何信息或帮助都会有所帮助。

我没有使用任何框架,这是 vanilla JS 的实际应用:

// CONTROLLER:

 constructor(model, view) {
    this.view = view;
    this.model = model;

    // Init here:
    this._cycleHeaderFooter();
    this._refreshActiveElements();
    this.view.bindToTop(this._handleToTop);
    this.view.bindNavClick(this._handleNavClick);
    this.view.bindObserver(this._handleObserver);
    
  }

_handleNavClick = clicked => {
    //View adjustment here
    // Unobserve first before resetting ? 
    this.view.resetNavigation();
    this.view.displaySection(clicked);
    this._refreshActiveElements();
    this.view.observe();
    this.view.displayFooter();
    this.view.activateNav(clicked);

  }
const app = new Controller(new Model(), new View());

export default class View {
  constructor() { }

  bindObserver(fn){
    // DOM, EVENTS,
 
    fn(this.activeHeading2);
}

  observe(activeHeading2){
    const toggleObserver= (obs, img) =>{
      console.log(obs);
      if (obs === 'hide') {
        this.main__topEl.classList.add('inactive');
        this.headerEl.classList.remove('stickyHeader');
      }
      if (obs === 'show') {
        this.main__topEl.classList.remove('inactive');
        this.headerEl.classList.add('stickyHeader');
      }
      if (obs === 'img') {
        // console.log(img.dataset.src);
        img.src = img.dataset.src;
        // Remove blur filter .lazy-img class
        img.classList.remove('lazy-img');
      }
    }
        const callback = function (entries, observer) {
      const [entry] = entries;

    
      if (entry.target === activeHeading2) {
        entry.isIntersecting ? toggleObserver('hide') : toggleObserver('show');
      }
    }
    const options = {
      root: null,
      threshold: 0,
    }
    let heading2Obs = new IntersectionObserver(callback, options);
    
    heading2Obs.unobserve(this.activeHeading2);
    heading2Obs.observe(this.activeHeading2);
  }
}

不确定为什么视图会被旧值卡住?

要在 class 的实例化上运行代码,您需要一个名为contructor not construction的方法。

同样在您的代码中,传递给构造函数的view参数与this.view ,您需要分配它。 请参阅下面的代码作为我的意思的示例。


class Controller {
  constructor(model, view) {
     this.view = view;
     this.view.bindObserver(this._handleObserver);
  }
 _handleObserver = (activeHeading2) => {
    this.view.observe(activeHeading2);
  }
}

Trick to MVC Architecture 知道如何导入每个 JavaScript class 以便其他模块可以访问它。 例子:

class 查看{

}

导出默认新类();

--> 然后在 controller: import view from './view.js'

这将允许 controller 查看 class 中的所有元素和方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM