user0103
user0103

Reputation: 1272

JS / jQuery objects

I'm writing a simple notifications system but I'm just learning JS / jQuery (front-end is new for me) and I have problem. I wrote following code:

 (function ($) {

    var notification = function(title, msg, duration) {
        this.element = $('<div class="notification"><h3>' + title + '</h3><div class="notification_body">' + msg + '<br/><i>(для скрытия уведомления кликните здесь два раза)</i></div></div>');
        this.element.dblclick(notification.hide);
        $('#notifications_bar').prepend(this.element.hide().fadeIn(1000));
    }

    notification.hide = function() {
        var $this = this;
        this.element.fadeOut(1000, function () {
            $this.element.remove();
        })
    }

    $.extend({
        notify: function(title, msg, duration) {
            return new notification(title, msg, duration);
        }
    });
})
    (jQuery);

But there is an error in method notification.hide: this.element is undefined. Can you explain me where the error? Thank you.

Upvotes: -1

Views: 87

Answers (1)

Matt
Matt

Reputation: 75317

When you pass a function which was attached to an object directly, the function forgets which object it was attached to (and therefore the value of this changes). This is because the value of this is not resolved until the function is invoked.

Instead, use the same approach you used for your fadeOut function (storing a reference to this, and using it inside an anonymous function;

var $this = this;
this.element.dblclick(function () {
    $this.hide();
});

Alternatively, you can use jQuery.proxy() or Function.prototype.bind() (ES5-complient browsers only) which force a value of this on the function, no matter where it is attached to later:

this.element.dblclick(jQuery.proxy(notification.hide, this));

Upvotes: 4

Related Questions