Jump to content

Recommended Posts

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);		
		}		
	}
Link to comment
https://forums.phpfreaks.com/topic/296085-accessing-event-more-elegantly/
Share on other sites

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 by requinix
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.