Friday, 15 January 2010

javascript - Binding 'this' and getting this -



javascript - Binding 'this' and getting this -

$('.btn-delete').on('click', this.confirm.bind(this));

above, on click runs:

p.confirm = function(e) { if(!$(this).hasclass('danger')){ $(this).addclass('danger'); $(this).bind('mouseleave',function(){ $(this).removeclass('danger'); $(this).unbind('mouseleave'); }); } else{ this.delete(); } };

i'm having problem this. need button need access method (this.delete). i've tried bind faisl work.

any ideas?

assuming i'm understanding question correctly, want able pass clicked element this p.confirm function. should able using call, or using p.confirm handler:

class="lang-js prettyprint-override">// using phone call $('.btn-delete').on('click', function (e) { p.confirm.call(this, e); }); // handler $('.btn-delete').on('click', p.confirm);

assuming this.delete p.delete, utilize call in handler pass clicked element this delete method:

class="lang-js prettyprint-override">p.confirm = function (e) { var self = $(this); // cache lookup, "this" clicked element if (!self.hasclass('danger')) { self.addclass('danger'); self.bind('mouseleave', function () { self.removeclass('danger'); self.unbind('mouseleave'); }); } else { p.delete.call(this); // pass clicked element utilize "this" in p.delete } };

javascript jquery

No comments:

Post a Comment