Reputation: 157
I have an object with 3 elements bound in one group and I need to remove this object (or at least it's graphical representation — the group) when green rectangle is clicked. The a.click() works, but c.click() doesn't and I'd like to know why:
var s = Snap(500, 500);
function myObj() {
this.g = s.group();
this.drawIt = function() {
var a = s.rect(0, 0, 50, 50, 0, 0).attr({'fill':'#E82941'}),
b = s.rect(20, 20, 50, 50, 0, 0).attr({'fill':'#FF6E00'}),
c = s.rect(40, 40, 50, 50, 0, 0).attr({'fill':'#00C049'});
this.g.append(a, b, c);
a.click(function(e){this.attr({'fill':'#000'});});
c.click(this.killIt);
}
this.killIt = function() {
this.g.remove();
}
}
var obj = new myObj();
obj.drawIt();
Snap.svg 0.3.0.
…
Solved: http://codepen.io/GeMir/pen/KwbBqV
Upvotes: 3
Views: 5467
Reputation: 266
Its the problem of closure, the this
inside the c.click
handler doesn't represent myObj
.
Declare a variable var that=this;
inside the constructor myObj
like below
function myObj() {
var that = this;
this.g = s.group();
this.drawIt = function() {
var a = s.rect(0, 0, 50, 50, 0, 0).attr({'fill':'#E82941'}),
b = s.rect(20, 20, 50, 50, 0, 0).attr({'fill':'#FF6E00'}),
c = s.rect(40, 40, 50, 50, 0, 0).attr({'fill':'#00C049'});
this.g.append(a, b, c);
a.click(function(e){this.attr({'fill':'#000'});});
c.click(function(e){that.killIt()});
}
this.killIt = function() {
this.g.remove();
}
}
var obj = new myObj();
obj.drawIt();
If you declare a function inside another function, the this
variable will not be the same as that of parent function. in this case, it will be pointed to the c
object, In the case of a.click
, as the this
is pointed to a
, it worked.
Upvotes: 3