Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript class not scoping as expected
    primarykey
    data
    text
    <p>Hoping someone can point me in the right direction.</p> <p>I'm not new to OOP but I am not as familiar with how it works in Javascript. I understand the notion that classes in js are objects.</p> <p>I'm writing a script that will write some html and allow the user to add or remove some elements. Everything works fine except when you click on "Add Checkbox" for any of the instances the html is updated in the last instance as opposed to itself (this is what leads me to believe there is some kind of scoping or encapsulation failure).</p> <p>I have simplified the problem and posted a fiddle, click on "Add Checkbox" for the "colors" instance and you'll see that the html is added to the "animals" group instead. Note my js comment on line 25.</p> <p><a href="http://jsfiddle.net/XrJ3D/" rel="nofollow">http://jsfiddle.net/XrJ3D/</a></p> <pre><code>var CheckboxGroup = function(label){ return this.init(label); } CheckboxGroup.prototype = { type: "checkbox", label: null, description: null, $label: null, init: function(label){ if(!label) label = "Checkboxes"; self = this; this.$wrap = $("&lt;div class='checkBoxGroup'&gt;&lt;/div&gt;"); this.$label = $("&lt;div&gt;"+label+"&lt;/div&gt;").appendTo(this.$wrap); this.$options = $("&lt;div&gt;&lt;/div&gt;").appendTo(this.$wrap); this.$add = $("&lt;div class='n'&gt;Add Checkbox&lt;/div&gt;").appendTo(this.$wrap); this.$add.click(function(){ self.addOption("New Option"); }); this.options = []; return this; }, addOption: function(label){ $option = $("&lt;div class='c'&gt;&lt;input type='checkbox' name='"+label+"'&gt;&lt;span class='l'&gt;"+label+"&lt;/span&gt;&lt;/div&gt;").appendTo(this.$options); $remove = $("&lt;span class='rm'&gt;x&lt;/span&gt;").appendTo($option); $remove.click(function(){ var r=confirm("Remove Option?"); if (r==false) return; $(this).parents('.c').remove(); }); this.options.push($option); return $option; }, get: function(){ return this.$wrap; } } // === CREATE SOME INSTANCES === a = new CheckboxGroup("Colors"); a.addOption('red'); a.addOption('green'); a.addOption('blue'); $('body').append(a.get()); b = new CheckboxGroup("Animals"); b.addOption('dog'); b.addOption('cat'); $('body').append(b.get()); </code></pre> <p>Thanks for any insight.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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