Created
April 9, 2019 23:16
-
-
Save Maxcutex/9ca985dccb867562ea4abc757e8d38bd to your computer and use it in GitHub Desktop.
Election Project - Client applicaiton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App = { | |
web3Provider: null, | |
contracts: {}, | |
account: '0x0', | |
init: function() { | |
return App.initWeb3(); | |
}, | |
initWeb3: function() { | |
if (typeof web3 !== 'undefined') { | |
// If a web3 instance is already provided by Meta Mask. | |
App.web3Provider = web3.currentProvider; | |
web3 = new Web3(web3.currentProvider); | |
} else { | |
// Specify default instance if no web3 instance provided | |
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545'); | |
web3 = new Web3(App.web3Provider); | |
} | |
return App.initContract(); | |
}, | |
initContract: function() { | |
$.getJSON("Election.json", function(election) { | |
// Instantiate a new truffle contract from the artifact | |
App.contracts.Election = TruffleContract(election); | |
// Connect provider to interact with contract | |
App.contracts.Election.setProvider(App.web3Provider); | |
return App.render(); | |
}); | |
}, | |
render: function() { | |
var electionInstance; | |
var loader = $("#loader"); | |
var content = $("#content"); | |
loader.show(); | |
content.hide(); | |
// Load account data | |
web3.eth.getCoinbase(function(err, account) { | |
if (err === null) { | |
App.account = account; | |
$("#accountAddress").html("Your Account: " + account); | |
} | |
}); | |
// Load contract data | |
App.contracts.Election.deployed().then(function(instance) { | |
electionInstance = instance; | |
return electionInstance.candidatesCount(); | |
}).then(function(candidatesCount) { | |
var candidatesResults = $("#candidatesResults"); | |
candidatesResults.empty(); | |
for (var i = 1; i <= candidatesCount; i++) { | |
electionInstance.candidates(i).then(function(candidate) { | |
var id = candidate[0]; | |
var name = candidate[1]; | |
var voteCount = candidate[2]; | |
// Render candidate Result | |
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>" | |
candidatesResults.append(candidateTemplate); | |
}); | |
} | |
loader.hide(); | |
content.show(); | |
}).catch(function(error) { | |
console.warn(error); | |
}); | |
} | |
}; | |
$(function() { | |
$(window).load(function() { | |
App.init(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment