简体   繁体   English

jQuery函数中触发了多个事件

[英]Multiple events fired in jquery function

I have html grid table consisting of comment link in each row.Clicking on any one opens a bootstrap modal with textbox and save button.So I wrote a library consisting of functions related to that comment system.Below is basic code. 我有每行包含注释链接的html网格表。单击任何一个都会打开一个带有文本框和保存按钮的引导模式,因此我编写了一个包含与该注释系统相关的功能的库,下面是基本代码。

HTML : HTML:

        <td><a class="addComment"  data-notedate="somevalue" data-toggle='modal'  href='#addnotesdiv' data-oprid="somevalue" data-soid="somevalue"  data-type="1"><i class="fa fa-comments-o fa-2"></i></a></td> ..... n

JS : JS:

    var Inventory={};

Inventory.notes={
defaults:{
                        type:'1',
                        soid:0,
                        operator_id:0,
                        date:'',
                        target:'div#addnotesdiv',
                  },
init:function()
{
   var self=this;

   $('div#addnotesdiv').on('show.bs.modal',function(e){
            self.getandsetdefaults(e);
            self.setmodalelements(e);
            self.getNotes();
            self.addnote();
            self.activaterefresh();
   });


},
getandsetdefaults:function(e)
{
     this.defaults.soid = $(e.relatedTarget).data('soid');
     this.defaults.operator_id=$(e.relatedTarget).data('oprid');
     this.defaults.type=$(e.relatedTarget).data('type');
     this.defaults.date=$(e.relatedTarget).data('notedate');

},
setmodalelements:function(e)
{
    $(e.currentTarget).find('#notesthread').empty();
    $(e.currentTarget).find('input#inpnotesoid').val(this.defaults.soid);
    $(e.currentTarget).find('input#inpnoteoprid').val(this.defaults.operator_id);
    $(e.currentTarget).find('input#inpnotetype').val(this.defaults.type);
},
addnote:function()
{
         var self=this;

        $('button#btnaddnote').on('click',function(){

            var message=$(self.defaults.target).find('textarea#addnotemsg').val();
            var soid=$(self.defaults.target).find('input[type=hidden][id=inpnotesoid]').val();
            var note_date=$(self.defaults.target).find('input#addnotedate').val();
            var oprid=$(self.defaults.target).find('input[type=hidden][id=inpnoteoprid]').val();
            var type=$(self.defaults.target).find('input[type=hidden][id=inpnotetype]').val();


               if(message=="" || soid=="" || note_date=="")
                    {
                        alert("Fill all details");
                        return;
                    }

              var savenote=$.post(HOST+'notes/save',{message:message,soid:soid,note_date:note_date,type:type,operator_id:oprid});

                savenote.done(function(res){

                res=$.parseJSON(res);

                if(res.status && res.error){
                    alert(res.message);
                    return;
                }
                if(res.status && res.type)
                {
                  $('div#addnotemsg').showSuccess("Done").done(function(){self.getNotes();});
                  $('div#addnotesdiv').find('textarea#addnotemsg').val('');
                }
                else
                {
                $('div#addnotemsg').showFailure("Error");
                }
                });

        });


},
getNotes:function()
{
      $('button#btnrefreshcomments i').addClass('glyphicon-refresh-animate');

       var getnotes=$.getJSON(HOST,{soid:this.defaults.soid,type:this.defaults.type,note_date:this.defaults.date,operator_id:this.defaults.operator_id});

        getnotes.done(function(res){
          if(res.status && res.data.length)
          {
             --somecode---
          }
       });
},
activaterefresh:function(){

      var self=this;

     $(document).on('click','#btnrefreshcomments',function(){
               $('#notesthread').empty();
                self.getNotes();
            return false;
        });

        return false;
}

}

In Order to activate this functionality on that page I wrote 为了激活该功能,我写了

     Inventory.notes.init();

Above code works perfectly when I open modal once but when I close that same modal and open it again but by clicking on different link all events are fired twice,thrice and so on.Number of events fired is equal to number of times modal opened on that page. 上面的代码在我打开模态一次时很完美,但是当我关闭相同的模态然后再次打开它时,通过单击不同的链接,所有事件都被触发两次,三次等等。被触发的事件数等于在其上模态打开的次数。该页面。 Is there any thing wrong in code Or any other way to perform this same task. 代码或执行此相同任务的任何其他方式有什么问题吗?

I know this is not a plugin all I wanted was to store all functionality related to comment system under one roof as library. 我知道这不是我想要的一个插件,而是将与注释系统相关的所有功能存储在一个库中。

every time you open the modal box, it triggered show.bs.modal event, then all methods was exec again, including the event bindings. 每次打开模式框时,它都会触发show.bs.modal事件,然后所有方法都再次执行,包括事件绑定。 eg event bind in [addnote] 例如[bind]中的事件绑定

$('div#addnotesdiv').on('show.bs.modal',function(e){
    self.getandsetdefaults(e);
    self.setmodalelements(e);
    self.getNotes();
    self.addnote();
    self.activaterefresh();
});

Problem was whenever modal was shown getNotes,addnote,activatereferesh functions were called but when the modal was reopened again this functions are called again so thats twice and so on.Putting it in more simpler way is there were multiple listeners attached to single element without destroying previous one because my init function was called many times. 问题是每当显示模式时都会调用getNotes,addnote,activatereferesh函数,但是当再次重新打开模式时,将再次调用该函数,以便两次执行,依此类推。以更简单的方式放置它是将多个侦听器附加到单个元素而不破坏上一个,因为我的init函数被多次调用了。

At last there were two solutions in both I need to unbind events or attach them only once.Got idea from here 最后有两个两种解决方案,我需要解除绑定事件或附加它们只once.Got想法在这里

1) Modified Init function with below code and added one unbind listener function 1)使用以下代码修改了Init函数,并添加了一个取消绑定的侦听器函数

init:function(selector)
{
   var self=this;

   $(self.defaults.target).on('show.bs.modal',function(e){
            self.getandsetdefaults(e);
            self.setmodalelements(e);
            self.getNotes();
            self.addnote();
            self.activaterefresh();

   });

   $(self.defaults.target).on('hide.bs.modal',function(e){
           self.unbindlistners();
   });
}
   unbindlistners:function()
{
      var self=this;
     $('#btnrefreshcomments').unbind('click');
     $('button#btnaddnote').unbind('click');

      return false;
}

}

2) Place event binding function outside show.bs.modal 2)将事件绑定函数放在show.bs.modal之外

 init:function(selector)
{
   var self=this;

   $(self.defaults.target).on('show.bs.modal',function(e){
            self.getandsetdefaults(e);
            self.setmodalelements(e);
   });
  self.getNotes();
  self.addnote();
  self.activaterefresh();
}

There is small catch in second solution that is when first time my DOM is loaded function getNotes function is called with default values. 在第二个解决方案中有一个小问题,那就是第一次加载DOM时使用默认值调用getNotes函数。

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

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