From 73f96aa0d51ec5f9ed190bae4f72f980aed9c420 Mon Sep 17 00:00:00 2001 From: Stefan Thomas Date: Wed, 13 Feb 2013 18:32:36 +0100 Subject: [PATCH] JS: Account class keeps track of AccountRoot entry. --- src/js/account.js | 54 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/src/js/account.js b/src/js/account.js index 49e35025ea..1bfff1560d 100644 --- a/src/js/account.js +++ b/src/js/account.js @@ -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