Refactoring JavaScript help

Soldato
Joined
27 Oct 2006
Posts
6,972
Location
London
OK I'm no JS coder but yay or nay to this || which version do you prefer ?....

Original code
Code:
function myupdatebart2(){
	if ($('.on_off :checkbox').prop('checked') == false) {
		socket.emit('updatebart2', false);
	} else {
		socket.emit('updatebart2', true);
	}
};
$('.on_off :checkbox').iphoneStyle({ onChange : myupdatebart2 });

Revision 2 - No point to this ? {works}

$('.on_off :checkbox').iphoneStyle({ onChange : function () { $('.on_off :checkbox').prop('checked') == false ? socket.emit('updatebart2', false) : socket.emit('updatebart2', true);} });

Revision 3 - Probably the best candidate {works}

$('.on_off :checkbox').iphoneStyle({ onChange : function () { socket.emit('updatebart2', $('.on_off :checkbox').prop('checked'));} });

Revision 4 - Makes obvious sense but the param needs a reference to a function and hence fails {fail}

$('.on_off :checkbox').iphoneStyle({ onChange : socket.emit('updatebart2', $('.on_off :checkbox').prop('checked')) });
 
Associate
Joined
25 Jan 2009
Posts
1,342
Location
London
An alternative to revision 2..
Code:
$('.on_off :checkbox').iphoneStyle({ 
  onChange : function () { 
    $('.on_off :checkbox').prop('checked') ? socket.emit('updatebart2', true) 
      : socket.emit('updatebart2', false);
  } 
});

I think this is pretty clear, but it's down to preference really...

I think revision 3 is also pretty clear.
 
Soldato
Joined
18 Oct 2002
Posts
15,414
Location
The land of milk & beans
A shorter revision to doiks' revision 2:

Code:
$('.on_off :checkbox').iphoneStyle({ 
    onChange : function () { 
        socket.emit('updatebart2', $(this).prop('checked'));
    } 
});

Note that the '$(this)' in the handler function is crucial. It means you're passing the value of the checkbox which raised the event, not an array of all the 'on_off : checkbox' values
 
Back
Top Bottom