[英]How to detect an account change in MetaMask using Meteor and web3?
我正在使用流星創建DApp,其中templateVar顯示一個帳戶地址。
在JavaScript中使用web3
函數,我定義了updateInterface()
方法,如下所示:updateInterface()
但是,由於該方法是一個循環,我似乎無法在Template.foo.events
內部觸發事件。 該方法的工作,因為我能夠alert(res)
的結果通知到屏幕上。
有人能指出我正確的方向嗎? 干杯
編輯:添加了template.oncreated
函數,並且函數updateInterface()
置於oncreated
,helper和events方法之外。
Template.foo.onCreated(function fooOnCreated() {
this.account= new ReactiveVar(0);
});
Template.foo.helpers({
account() {
var template = Template.instance();
myContract = web3.eth.contract(ABIArray).at(contractAddress);
var result = web3.eth.getCoinbase(function(err, res) {
TemplateVar.set(template, "person", res);
});
},
});
Template.foo.events({
// not sure what to place here
});
var account = web3.eth.accounts[0];
var accountInterval = setInterval(function() {
if (web3.eth.accounts[0] !== account) {
account = web3.eth.accounts[0];
updateInterface();
}
}, 100);
function updateInterface() {
var template = Template.instance();
var result = web3.eth.getCoinbase(function(err, res) {
alert(res);
TemplateVar.set(template, "account", res);
});
}
事件的問題在於它需要一個事件,而metamask檢測功能每100毫秒檢測一次帳戶更改,但我不確定將updateInterface()
方法放在何處。
TemplateVar指向此處。
<head>
<body>
<div id="section">
{{>foo}}
</div>
</body>
</head>
<template name="foo">
<div id="location">
<p>Currently logged in as: {{account}} {{TemplateVar.get
"account"}} </p>
</div>
</template>
我認為您應該將間隔循環放在onCreated
,而不是檢查account !== web3.eth.accounts[0]
,而應檢查self.account.get() = web3.eth.accounts[0]
像這樣
Template.foo.onCreated(function fooOnCreated() {
this.account= new ReactiveVar(0);
this.account.set(web3.eth.accounts[0]);
var self = this;
var accountInterval = setInterval(function() {
if (web3.eth.accounts[0] !== self.account.get()) {
self.account.set(web3.eth.accounts[0]);
}
}, 500);
});
並且由於它是ReactiveVar
您不必調用更新函數。 模板將隨着使用的值而自動更新。
我沒有測試過,但我認為它應該像這樣工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.