2013-03-09 4 views
0

간단한 알림 시스템을 작성하고 있지만 JS/jQuery (프론트 엔드는 새로운 기능)를 학습하고 있으며 문제가 있습니다.JS/jQuery 객체

(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); 

을하지만 방법 notification.hide에 오류가 있습니다 : 나는 다음 코드 작성 this.element가 정의되어 있지 않습니다. 어디에서 오류를 설명 할 수 있습니까? 감사합니다.

+0

이 너무 html 코드를 공유 할 수 있습니다 –

+0

톤를? 그의 "notification.prototype.hide = function() {"이 더 좋고 메모리 효율적인 방법입니다. "notification.hide = function() {", 원래 문제에 대한 대답은 아래에서 Matt – Ankit

답변

4

함수를 직접 객체에 잊어가 부착 된 개체 첨부 된 기능을 통과하면 (따라서 this 변화의 값). 값인은 함수가 호출되기 전까지 해결되지 않기 때문입니다.

대신에, 당신은 당신의 fadeOut 기능에 사용되는 것과 동일한 방식 (this에 대한 참조를 저장하고, 익명 함수 내에서 그것을 사용하는 사용, 또는

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

을, 당신은 jQuery.proxy() 또는 Function.prototype.bind() (ES5-에 적합하게 대응을 사용할 수 있습니다 브라우저 만) 기능에 this의 값을 강제하는 상관없이 나중에 부착된다 :

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

감사합니다. 콜백 함수가 작동하지 않지만 jQuery.proxy가 완벽하게 작동합니다. – user0103

+1

@DarkNeo : 도움이 된 것을 기쁘게 생각합니다. 분명히 토요일에 코드 작성을하기에는 너무 이르다. 콜백 방식이 작동하지 않는다는 것이 맞다. 그에 따라 내 대답을 업데이트했습니다. – Matt

+0

매트, 내 코드 좀 봐 줄래? 나는 그 질문을 갱신했다. – user0103