用于事件处理的面向对象javascript

用于事件处理的面向对象javascript,javascript,jquery,oop,Javascript,Jquery,Oop,嗨,我尝试模块化我的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-lis

嗨,我尝试模块化我的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>
我想做这样的东西

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

HomePostList.prototype.init() {
    //event handling
}
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)));
});

我之所以想让它成为OOP,是因为我想在组件之间进行通信,而且我不必多次重写$widget.find('.home post list hide').hide()。

您可以这样做

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

HomePostList.prototype.init() {
    //event handling
}
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)));
});
从评论中可以看出,您在这里真正想要做的是缓存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不像布尔false那样,你可以说'false',每个人都知道你在说什么。添加流行语“模块化”也没有多大帮助。询问问题的方式应避免预先假定您知道解决方案。

我不明白。OOP只是构建代码的一种方式。这里显示的任何内容都不意味着OOP,并且通过使用OOP,这不需要您进行服务器端渲染。您可以使用AJAX连接服务器端。我想将我的javascript结构化为面向对象,目前我只需一次处理一个事件function@NiharSarkar我的问题中没有提到任何ajax,我只是想知道如何将我的javascript代码构造成面向对象的。我怎样才能使我的代码更蓝。OOP只是一个短语,它根据上下文有许多不同的含义。这也不是编码成功的神奇公式。你发布的代码没有任何问题。后期编辑:您希望获得清晰易读的jquery,并将其变成一团糟?故意的?嗯,好吧,但我不知道Homepostlist的ID,这取决于服务器端generated@RobertLimanto我编辑了示例代码以按类查找元素。我想是的,但我已经有一段时间没有用JS写东西了。)谢谢,我还有一个问题,请帮帮我