Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript equivalent to C#s "protected"
    text
    copied!<p>The code below uses Javascript to create a base class, <code>eventRaiser</code>, that has the internals needed to allow clients to subscribe to events, <strong>and subclasses</strong> to raise these events. The idea is that other classes, like <code>ThingWithEvent</code>, will inherit from <code>eventRaiser</code> and expose the subscribe method, and fire off the raise method internally. The jQuery init function demonstrates this.</p> <p>The way this is written, there's nothing stopping a client from directly raising an event. In other words, adding <code>er.raise("Y");</code> to the jQuery init function causes the Y event to be raised without difficulty. </p> <p>Ideally I'd like to make it so that outside code, interacting with <code>eventRaiser</code> through some class that inherits from it, with can only subscribe to events, and not raise them. </p> <p><strong>In other words I'd like <code>raise</code> to be the equivalent of C# <code>protected</code>—visible only to itself, and classes that inherit from it.</strong></p> <p>Is there some slick ninja closure I should use to achieve this, or should I recognize that Javascript is not meant to incorporate OO Encapulation, rename <code>raise</code> to <code>_raise</code> to imply to client code that <code>_raise</code> is private and should not be invoked, and move on?</p> <pre><code> $(function() { var er = new ThingWithEvent(); er.subscribe("X", function() { alert("Hello"); }); er.subscribe("X", function() { alert("World"); }); er.subscribe("Y", function() { alert("Not Called"); }); er.doSomething("X"); }); function eventRaiser() { var events = {}; this.subscribe = function(key, func) { if (!events[key]) events[key] = { name: key, funcs: [] }; events[key].funcs.push(func); }; this.raise = function(key) { if (!events[key]) return; for (var i = 0; i &lt; events[key].funcs.length; i++) events[key].funcs[i](); }; } function ThingWithEvent() { eventRaiser.call(this); var self = this; this.doSomething = function() { alert("doing something"); self.raise("X"); } } function surrogate() { } surrogate.prototype = eventRaiser; ThingWithEvent.prototype = new surrogate(); ThingWithEvent.prototype.constructor = ThingWithEvent; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload