-2

Get Object function name from event list on IE works fine in Chrome btw

Example

var foo = {
 fookeydown:function(e){
   e.which;
   ... do something
 }
}
$(document).on("keydown",foo.fookeydown)
$._data(document,"events").keydown[0].handler.name // return me fookeydown in Chrome 
 but ie is nut 

1 Answers1

0

You are trying to access a function's property function.name, which is not defined for IE. You could try the following implementation to define it (Notice the function name given to the function in foo):

if (!(function f() {}).name) {
  Object.defineProperty(Function.prototype, 'name', {
    get: function() {
      var name = (this.toString().match(/^function\s*([^\s(]+)/) || [])[1];
      Object.defineProperty(this, 'name', {
        value: name
      });
      return name;
    }
  });
}

var foo = {
  fookeydown: function fookeydown(e) {
    console.log(e.which, 'keydown');
    console.log($._data(document, "events").keydown[0].handler.name);
  }
};
$(document).on("keydown", foo.fookeydown);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Alternative, searching in foo.fooProp:

var foo = {
  fooProp: {
    foofookeydown: function(e) {
      console.log(e.which, 'keydown');
      console.log($._data(document, "events").keydown[0].handler.name);
    },
    init: function() {
      $(document).on("keydown", this.foofookeydown);
    },
  },
  init: function() {
    this.fooProp.init()
  }
};

if (!(function f() {}).name) {
  Object.defineProperty(Function.prototype, 'name', {
    get: function() {
      var name = '';
      var values = Object.keys(foo.fooProp).map(function(e) {
        return foo.fooProp[e]
      });
      if (values.length > 0) {
        if (values.indexOf(this) > -1)
          name = Object.keys(foo.fooProp)[values.indexOf(this)];
      }
      Object.defineProperty(this, 'name', {
        value: name
      });
      return name;
    }
  });
}

foo.init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
shrys
  • 5,860
  • 2
  • 21
  • 36