2016-08-15 60 views
-2

您好我试图模块化我的JavaScript,并使其面向对象,但我感到困惑时,我试图做与多个实例的组件。面向对象的事件处理的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标识(#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的原因(“家庭后列表隐藏”)。隐藏() 多次。

+2

我没跟着。 OOP只是构建代码的一种方式。您在那里显示的任何内容都暗示了OOP,并且通过使用OOP,并不需要您执行服务器端渲染。 –

+0

您可以使用AJAX连接服务器端。 –

+0

我想构建我的JavaScript成为面向对象,目前我只是在一个函数中做一个事件 –

回答

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))); 
}); 
+0

嗯,好吧,但我不知道Homepostlist的ID,它取决于服务器端生成的内容 –

+0

@RobertLimanto我编辑了示例代码以按类查找元素。 –

+0

哇,它可能工作,我会先尝试.. –

1

它看起来(从评论),你是什么真正想在这里做的是缓存您访问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(); 
    }; 
}); 

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