-1

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.

2
  • can you share html code too ? Commented Mar 9, 2013 at 10:26
  • this "notification.prototype.hide = function() {" is better and memory efficient way then "notification.hide = function() {", Answer to your original problem is below from Matt Commented Mar 9, 2013 at 10:38

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, Matt. Callback function doesn't work, but jQuery.proxy works perfectly.
@DarkNeo: Glad it helped. Clearly 10:30 is too early for me to be writing code on a Saturday, as you were right about the callback approach not working; I've updated my answer accordingly.
Matt, can you take a look at my code? I updated the question.
@DarkNeo: Code reviews like this are better suited for codereview.stackexchange.com... if you post it on there, and provide me a link, I'll be happy to add my 2 cents on there as an answer :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.