1

I have a select element with id settings-select.These are the two different ways I am binding event.Why is 'this' value not bound to select element even after using 'bind' in second method.

   1. 
    $('body').on( 'change', '#settings-select', function() {
        console.log( $(this).val ); // outputs correct select value
    });

   2.
    $('body').on( 'change', '#settings-select', selectSettings.bind( this ) );

    function selectSettings() {
        console.log( $(this).val() );// Throws error. this -> window object. Why?
    }
0

3 Answers 3

2

When using bind, this doesn't refers to current element. It refers to window object.

You just need to pass the function reference

$('body').on( 'change', '#settings-select', selectSettings)

As per comment, some argument to selectSettings. You can use event.data

var x = 1;
$('body').on('change', '#settings-select', {
  value: x
}, selectSettings)

function selectSettings(event) {
  console.log(event.data.value, $(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='settings-select'>
  <option>1</option>
  <option>2</option>
</select>

Sign up to request clarification or add additional context in comments.

4 Comments

Why does $(this).val() works inside selectSettings function in this case?Can you please explain?
In this scenario, this is set with current element context so it works
How can I pass arguments to selectSettings?
@johndoe, api.jquery.com/event.data updated answer with snippet
2

Throws error. this -> window object. Why?

Because, $('body').on( 'change', '#settings-select', selectSettings.bind( this ) ); This particular code was executed in window's context. So there this would point to window.

And a rule behind bind function is, once you bound a context to a function using bind, then that wouldn't be changed to any after that.

Comments

0

In the second method just pass the function callback reference like this

$('body').on( 'change', '#settings-select', selectSettings)

yes both are same functionality, But there difference between the First method and second one,

1) It is an anonymous callback function.

 $('body').on( 'change', '#settings-select', function() {
        console.log( $(this).val() ); // outputs correct select value
 });

2) If you want reusable function go to second method then where want you to bind the same function

$('body').on( 'change', '#settings-select', selectSettings);

    function selectSettings() {
        console.log( $(this).val());
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.