swisnl / jQuery-contextMenu

jQuery contextMenu plugin & polyfill
https://swisnl.github.io/jQuery-contextMenu/
MIT License
2.25k stars 744 forks source link

How can i rebind the event and overwrite items callback ? #746

Closed zhangxh1023 closed 3 years ago

zhangxh1023 commented 3 years ago
<p class="first">right click here</p>
  <button id="rebind">rebind</button>

  <script>
    let editHandle = (key, opt) => {
      console.log('first bind');
    }
    const bindEvent = () => {
      $.contextMenu({
        selector: ".first",
        items: {
          "edit": {
            name: "edit",
            callback: editHandle
          }
        }
      });
    }
    bindEvent();
    $('#rebind').on('click', () => {
      editHandle = (key, opt) => {
        console.log('second bind');
      }
      // $('.first').contextMenu('update')
      // $('.first').off('contextmenu')
      // $('.first').unbind('contextmenu')
      bindEvent();
    })
  </script>

I want to change the items callback, or remove the bound events and rebind it. But it doesn't work.

Can anyone help me? Thanks.

zhangxh1023 commented 3 years ago

I try to find a solution from source code.

And it seems to slove my problem.


    $('#rebind').on('click', () => {

      // remove bound events before rebind.
      const selector = '.first';
      for (const key in $.contextMenu.menus) {
        if ($.contextMenu.menus[key].selector === selector) {
          $(document).off('contextmenu' + key, selector, $.contextMenu.handle.contextmenu);
          // delete $.contextMenu.menus[key];     // Maybe it can delete
        }
      }

     // xxxxxxxx

But i don't know if it has any other problems.