Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Calling 'this' within a JQuery event listener function

I am trying to refer to this (i.e. the ReactJS component) within a JQuery event callback:

var Component = React.createClass({
    func1: function(){
        $("#multi").multiselect({
            onChange: function(a, b){
                this.test();
            },
        });
    },
    test: function(){
         console.log("Calling a react component function");
    }
    ...
});

However it says:

TypeError: this.test is not a function

How to I refer to this within a JQuery event callback function?

like image 925
p_mcp Avatar asked Sep 10 '26 17:09

p_mcp


2 Answers

You'll need to bind the onChange callback to the context:

onChange: function(a, b) {
  this.test();
}.bind(this)

You could also use an arrow function:

onChange: (a, b) => {
  this.test()
}
like image 181
Dominic Avatar answered Sep 12 '26 06:09

Dominic


Here is a solution

var Search = React.createClass({ 
  componentDidMount: function() { 
  var that = this;
  $('#searchindexcheckinout').datepicker({
    language: 'fr',
	minDate: new Date(),
	firstDay: 0,
    onSelect: function(formattedDate, date, inst) { 
      that.GetResult();
    }
  });    
}, 
GetResult: function() {
  alert();
}, 
render: function() { 
       ...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
$('#searchindexcheckinout').datepicker({
  language: 'fr',
  minDate: new Date(),
  firstDay: 0
});
like image 28
OussamaChaib Avatar answered Sep 12 '26 06:09

OussamaChaib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!