【问题标题】:Object oriented javascript for event handling用于事件处理的面向对象的 javascript
【发布时间】:2016-08-15 16:55:46
【问题描述】:

您好,我尝试将我的 javascript 模块化并使其面向对象,但是当我尝试使用具有多个实例的组件时感到困惑。

我的代码是这样的

HTML 文件

   <div id="1" class="home-post-list" data-id="1">
         <div class="home-post-list-hide">
         </div>
   </div>
   <div id="2" class="home-post-list" data-id="2">
        <div class="home-post-list-hide">
         </div>

   </div>

上面的 HTML id (#1, #2) 是从服务器随机生成的。

这是当前的代码(不是 OOP),

$(document).on('click', '.home-post-list', function(e){ 
   var id = $(this).data('id');
   var $widget = $("#" + id);
   $widget.find('.home-post-list-hide').hide();
});

$(document).on('mouseover', '.home-post-list', function(e) {
      var id = $(this).data('id');
   var $widget = $("#" + id);
   $widget.find('.home-post-list-hide').show();
});

我想做这样的东西。

var HomePostList = function(){
    this.$widget = this.find('.home-post-list-hide');
    this.init();
};

HomePostList.prototype.init() {
    //event handling
}

我想使它成为 OOP 的原因,因为我想在组件之间进行通信,并且我不必多次重写 $widget.find('.home-post-list-hide').hide() .

【问题讨论】:

  • 我没有关注。 OOP 只是一种结构化代码的方式。您在那里显示的任何内容都没有暗示 OOP,并且通过使用 OOP,这不需要您进行服务器端渲染。
  • 您可以使用 AJAX 与服务器端连接。
  • 我想将我的 javascript 结构化为面向对象,目前我只在一个函数中执行一个事件
  • @NiharSarkar 我没有在我的问题中说任何 ajax,我只是想知道如何将我的 javascript 代码结构化为面向对象。
  • '我听说我的代码应该是蓝色的。我怎样才能让我的代码更蓝? OOP 只是一个短语,它根据上下文表示许多不同的东西。它也不是编码成功的某种神奇公式。您发布的代码没有任何问题。后编辑:您希望采用清晰易读的 jquery 并将其变成一团糟?故意的?

标签: javascript jquery oop


【解决方案1】:

你可以这样做。

var HomePostList = function($root){
    this.$root = $root;
    this.$widget = this.$root.find('.home-post-list-hide');
    this.init();
};

HomePostList.prototype.init() {
    //event handling
}


list = []
$(".home-post-list").each(function(el){
    list.push(HomePostList($(el)));
});

【讨论】:

  • 嗯,好吧,但我不知道 Homepostlist 的 id,这取决于服务器端生成的内容
  • @RobertLimanto 我编辑了示例代码以按类查找元素。
  • 我是这么认为的,但是我已经有一段时间没有用 JS 写东西了 ;)
  • 谢谢,我还有一个问题,请帮助我stackoverflow.com/questions/38961648/…
【解决方案2】:

看起来(来自 cmets)您真正在这里尝试做的是缓存您的 DOM 访问,这样您就不必一遍又一遍地查找元素。你可以用这样的模式来完成它:

$(document).on('click', '.home-post-list', (function(e) {
   var element = null // we'll lazily set this on the first event
   return function(e) {
     // by using the conditional here, find only gets executed once:
     // the first time the event fires.
     if (!element) {
        // note that instead of 'this' I'm using the event target.
        // the 'this' context is lost in handlers, that's why OOP
        // is arguably a sub-optimal fit here
        element = $("#" + $(e.currentTarget).data('id')).find('.home-post-list-hide');
     }
     element.hide();
   };
});

正如我上面所说,OOP 不像布尔假,你可以说“假”,每个人都知道你在说什么。添加流行语“模块化”也没有多大帮助。以一种避免预设您知道解决方案应该是什么的方式询问问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多