La ubicación de mi contrato es aquí
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);
}
function getInstructor() view public returns (string, uint) {
return (fName, age);
}
}
MI guión JS
window.addEventListener('load', function() {
if (typeof web3 !== 'undefined') {
console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
window.web3 = new Web3(web3.currentProvider);
} else {
//console.log('No Web3 Detected... using HTTP Provider')
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
//TO-DO
//Pop Up Model And Ask User download MetaMask
console.log('No web3? You should consider trying MetaMask!');
}
startApp();
});
function startApp() {
var CoursetroContract = web3.eth.contract(
[{ "constant": false, "inputs": [{ "name": "_fName", "type": "string" }, { "name": "_age", "type": "uint256" }], "name": "setInstructor", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "getInstructor", "outputs": [{ "name": "", "type": "string" }, { "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [{ "indexed": false, "name": "name", "type": "string" }, { "indexed": false, "name": "age", "type": "uint256" }], "name": "Instructor", "type": "event" }]
);
var Coursetro = CoursetroContract.at('0x96d2a2978d52287c2DffF0e2A40D12181223303C');
var instructorEvent = Coursetro.Instructor({ fromBlock: 0, toBlock: 'latest' });
instructorEvent.watch(function(error, result) {
if (!error) {
$("#loader").hide();
$("#instructor").html(result.args.name + ' (' + result.args.age + ' years old)');
} else {
$("#loader").hide();
console.log(error);
}
});
$("#button").click(function() {
$("#loader").show();
Coursetro.setInstructor($("#name").val(), $("#age").val(), function(error, result) {
if (!error) {
} else
console.log(error);
});
});
}
Cuando hago clic en el botón para llamar a la función setInstructor y luego se realiza la transacción, el evento no se activa. Por favor ayuda.
Si desea un watch
evento y no get
los eventos históricos, debe cambiar su declaración de evento a:
var instructorEvent = Coursetro.Instructor();
De lo contrario, se vería así:
var myEvent = contractInstance.myEvent({}, {fromBlock: 0, toBlock: 'latest'});
myEvent.get((error, events) => {
if (!error) {
function ShowResults(event) {
console.log('Argument 1: ' + event.args._arg1);
console.log('Argument 2: ' + event.args._arg2);
}
events.forEach(ShowResults);
} else {
console.log('Error');
}
});
shawn