2013-05-25 2 views
1

최근에 이벤트 구동 자바 스크립트로 놀았으며 내부 논리를 추상화하고 단순화하는 방법으로 자신의 이벤트를 수신하는 객체에 대해 좋은지 나쁜지 궁금해했습니다.자신의 이벤트를 듣는 자바 스크립트 객체

function MyModule(options) { 
    this.options = options; 
    this.data = {}; 

    this.setListeners(); 
    //... 
} 

MyModule.prototype = new EventEmitter; 
MyModule.prototype.constructor = MyModule; 

MyModule.prototype.updateBasket = function() { 
    var self = this, 
     url = this.options.url; 

    $.ajax(url) 
     .done(function(data) { 
      self.emit('basketupdate:success', data); 
     }) 
     .fail(function(jqxhr, textStatus, err) { 
      self.emit('basketupdate:error', err); 
     }) 
     .complete(function() { 
      self.emit('basketupdate:complete'); 
     }); 
}; 

MyModule.prototype.setListeners = function() { 
    var self = this; 

    this.on('basketupdate:success', function(data) { 
     // ... do something on success 
     self.data = data; 
    }); 

    this.on('basketupdate:success', function(data) { 
     // ... do something else on success 
     console.dir(data); 
    }); 

    this.on('basketupdate:error', function() { 
     // ... do something to handle the error 
    }); 
}; 

var module = new MyModule({ 
    url: '/path/to/request' 
}); 

module.updateBasket(); 

Ajax를 요청하는 간단한 모듈 :

은 다음 고려한다. 모든 논리를 해당 콜백에 넣거나 심지어 콜백을 내부 메서드에 쉽게 매핑 할 수 있습니다. 그러나 나는 코드를 단순화하기 위해이 접근법을 매우 좋아한다.

내가 고려하지 않은 방식으로 코드를 구성 할 때 단점이나 잠재적 인 문제가 있습니까? 아니면 다른 곳에서들을 수 있도록 의도 된 사건만으로는 반 패턴으로 여겨 질까요?

+0

아마 http://codereview.stackexchange.com/에서이 질문을 고려해야합니다. 나는이 코드의 잠재적 인 문제점을 보지 못했다. 모듈 자체와 외부에서 수신 대기하는 이벤트는 여러 jQuery 라이브러리에서도 수행된다. – migg

+0

감사합니다 - 나는 codereview에 대해 몰랐습니다! 내가 거기에 게시했습니다. – leepowell

답변

0

이렇게 할 수는 있지만 실제로 유용하지는 않습니다.

이 코드

읽기 단지 쉽게 :

MyModule.prototype.updateBasket = function() { 
    var self = this, 
     url = this.options.url; 

    $.ajax(url) 
     .done(this.done) 
     .fail(this.fail) 
     .complete(this.complete); 
}; 

MyModule.prototype.done = function(data) { 
    // Do something when done 
}; 

MyModule.prototype.fail = function(data) { 
    // Do something when request failed 
}; 

MyModule.prototype.complete = function(data) { 
    // Do something no matter what 
}; 

을 그리고 당신은 당신의 방법에 더 많은 의미있는 이름을 부여 할 수있다.

이벤트 이미 터는 함께 링크하지 않으려는 다른 객체로 재생할 때 유용합니다.

+0

나는이 단순화 된 맥락에서 동의한다. 그러나 객체가 커지고 복잡해지면'done'과 같은 메소드는 많은 다른 것들을 처리 할 수 ​​있습니다. 청취자를 사용하면 논리를보다 명확하게 유지하고 개별적인 관심사로 분리 할 수 ​​있습니다. 아이디어 만 가지고 놀 수 있습니다. – leepowell

+0

@leepowell 어쨌든 다른 이벤트에 대해 서로 다른 청취자를 갖게 될 것입니다. 기능을 사용하면 깨끗하고 분리 된 관심사를 원한다면 갈 수있는 방법입니다. 그것은 결국 그들이 발명 한 것입니다. –