JS: Account class keeps track of AccountRoot entry.

This commit is contained in:
Stefan Thomas
2013-02-13 18:32:36 +01:00
parent 7dd0ee6ed9
commit 4b7230a8b4

View File

@@ -13,11 +13,14 @@ var EventEmitter = require('events').EventEmitter;
var Amount = require('./amount').Amount;
var UInt160 = require('./uint160').UInt160;
var extend = require('extend');
var Account = function (remote, account) {
var self = this;
this._remote = remote;
this._account = UInt160.from_json(account);
this._account_id = this._account.to_json();
// Ledger entry object
// Important: This must never be overwritten, only extend()-ed
@@ -27,7 +30,7 @@ var Account = function (remote, account) {
if (Account.subscribe_events.indexOf(type) !== -1) {
if (!this._subs && 'open' === this._remote._online_state) {
this._remote.request_subscribe()
.accounts(this._account.to_json())
.accounts(this._account_id)
.request();
}
this._subs += 1;
@@ -39,8 +42,8 @@ var Account = function (remote, account) {
this._subs -= 1;
if (!this._subs && 'open' === this._remote._online_state) {
this._remote.request_unsubscribe([ 'transactions' ])
.accounts(this._account.to_json())
this._remote.request_unsubscribe()
.accounts(this._account_id)
.request();
}
}
@@ -49,11 +52,25 @@ var Account = function (remote, account) {
this._remote.on('connect', function () {
if (self._subs) {
this._remote.request_subscribe()
.accounts(this._account.to_json())
.accounts(this._account_id)
.request();
}
});
this.on('transaction', function (msg) {
var changed = false;
msg.mmeta.each(function (an) {
if (an.entryType === 'AccountRoot' &&
an.fields.Account === this._account_id) {
extend(this._entry, an.fieldsNew, an.fieldsFinal);
changed = true;
}
});
if (changed) {
self.emit('entry', self._entry);
}
});
return this;
};
@@ -79,6 +96,35 @@ Account.prototype.is_valid = function ()
return this._account.is_valid();
};
/**
* Retrieve the current AccountRoot entry.
*
* To keep up-to-date with changes to the AccountRoot entry, subscribe to the
* "entry" event.
*
* @param {function (err, entry)} callback Called with the result
*/
Account.prototype.entry = function (callback)
{
var self = this;
self._remote.request_account_info(this._account_id)
.on('success', function (e) {
extend(self._entry, e.account_data);
self.emit('entry', self._entry);
if ("function" === typeof callback) {
callback(null, e);
}
})
.on('error', function (e) {
callback(e);
})
.request();
return this;
};
exports.Account = Account;
// vim:sw=2:sts=2:ts=8:et