JavaScript method reference and call

I have JavaScript / jQuery code that watches for a “changed” event on a checkbox:

$(control).change(function() {
    alert("changed to: " + $(this).is(":checked"));
});

This works great.

I would like to create a link to the change () function for a specific object and call it indirectly, for example:

var onSomeChange = $(control).change;
onSomeChange(function() {
    alert("changed to: " + $(this).is(":checked"));
});

I need to call it indirectly because I want to switch the method that I assign onSomeChange to another, as the case may be. (The only purpose for onSomeChange is for illustration purposes only.)

This does not work. In Firebug, I get this error:

this.bind is not a function

How can I get a reference to an object method and call it without calling it directly from the object?

Background

Context may be significant; if there is a completely different way of doing what I want, that’s good too.

change JavaScript . ( ). ( , Firefox, , ) . , . ( , div ).

, , , change . jQuery radioChange().

, . ( , , , -, , , -). radioChanged() jQuery .

, (), radioChanged() . :

var change = $(control).is(":radio") ? $(control).radioChange : $(control).change;

, change , .

- , , ?

+3
2

:

, . , , $(control) , , , , $.

var $control = $(control);
var change = $control.change;
change.call( $control, 
    function() {
      alert("changed to: " + $(this).is(":checked"));
    }
);
+3

,

$(control).bind($(control).is(":radio") ? "radioChange", "change", function () {});
+2

Source: https://habr.com/ru/post/1748556/


All Articles