javascript - What is node's equivalent of Perl's magic `tie()` mechanism (hooking into/intercepting access to variables)? -
i'm looking example, intercepting access string, array , object variables user-defined callbacks/hooks:
class="lang-js prettyprint-override">var foo = []; tie( // hypothetical foo, { store: // callback triggered when assigning: foo[index] = value function(self, index, value) { if (value.match('fnord')) { self[index] = "nothing see here. move along."; return; } self[index] = value; }, fetch: // callback triggered when accessing: foo[index] function(self, index) { if (42 == index) { homecoming "this answer."; } homecoming self[index]; } } );
simple demo of working implementation of concept:
class="lang-perl prettyprint-override">package quux; utilize tie::array (); utilize base of operations 'tie::stdarray'; sub fetch { ($self, $index) = @_; homecoming 'this answer.' if 42 == $index; homecoming $self->[$index]; } sub store { ($self, $index, $value) = @_; if ($value =~ 'fnord') { $self->[$index] = 'nothing see here. move along.'; return; } $self->[$index] = $value; } bundle main; tie @foo, 'quux'; @foo = (undef) x 50; print $foo[42]; $foo[0] = 'fnord'; print $foo[0];
full documentation: tie (concept), tie()
(function), tie::array, magic
a rough equivalent functionality the proxy api. es6 feature, v8 provides "experimental" back upwards (start node --harmony
or --harmony-proxies
enable feature). here's snippet rewritten proxies:
var foo = (function() { var obj = {}; homecoming proxy.create({ set: function(self, index, value) { if (value.match(/fnord/)) { obj[index] = "nothing see here. move along."; return; } obj[index] = value; }, get: function(self, index) { if (42 == index) { homecoming "this answer."; } homecoming obj[index]; } }); })(); console.log(foo[42]); foo[0] = 'fnord'; console.log(foo[0]);
javascript node.js
No comments:
Post a Comment