Drongo_III Posted May 5, 2015 Share Posted May 5, 2015 Hi Guys I'm just wondering whether there's a more elegant way to access the event object in the following example. I realise I could use jquery's $.proxy method but lets say we hypothetically had to use call() it doesn't seem very clean to have to pass 'e' into the anonymous function and as a parameter on call(). So is there a better way to access the event object in this scenario? I know this is a bit of a pie in the sky question but I'm just keen to understand whether what follows is the only way or not. Thanks, Drongo $(document).ready(function(){ $('#tt').on('click', function(e){ test.init.call(test,e,'some text as extra param'); }); }); var test = { init: function(e, g){ e.preventDefault(); console.log(e); console.log(g); } } Quote Link to comment https://forums.phpfreaks.com/topic/296085-accessing-event-more-elegantly/ Share on other sites More sharing options...
requinix Posted May 6, 2015 Share Posted May 6, 2015 (edited) If you have to use .call then there's not much you can do because you're forcing yourself to call the function manually. And if you're doing that you might as well just pass e and the string at that time. Anything I can think of involves using more code so that you can use less code - pointless. What's wrong with .proxy? You could use it with event.data like $('#tt').on('click', $.proxy(test.init, test), 'some text as extra param'); var test = { init: function(e) { e.preventDefault(); console.log(e); console.log(e.data); } };Or write a wrapper like test.on('#tt', 'click', 'init', 'some text as extra param'); var test = { init: function(e) { e.preventDefault(); console.log(e); console.log(e.data); }, on: function(selector, event, handler, data) { $(selector).on(event, $.proxy(test[handler], test), data); } };(or for that matter, write a wrapper that uses the .call method) Edited May 6, 2015 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/296085-accessing-event-more-elegantly/#findComment-1510879 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.