[Ethereum] Event.watch not firing

solidityweb3js

I'm following this very simple web3 tutorial and Event.watch doesn't seem to fire when I click the button.

I can't figure it out.

Can someone please help?

pragma solidity ^0.4.18;

contract Coursetro {

   string fName;
   uint age;

   event Instructor(
       string name,
       uint age
    );

   function setInstructor(string _fName, uint _age) public {
       fName = _fName;
       age = _age;
       Instructor(_fName, _age); 
   }
}

and then JS:

var instructorEvent = Coursetro.Instructor();
instructorEvent.watch(function(error, result){
  alert(1);
});
$("#button").click(function() {
  Coursetro.setInstructor('a', 1);
});

alert never happens.

Best Answer

I had a similar issue and solved it by specifying the block range given by fromBlock and toBlock when defining the reference to the event in JS. So for your case, you could try the following:

var instructorEvent = Coursetro.Instructor({}, {fromBlock: startBlockNo, toBlock: 'latest'});
instructorEvent.watch(function(error, result){
    alert(1);
});

Note that only the first line is changed, I added the rest just for completeness.