2013-07-06 2 views
2

나는 하나의 페이지 ws++ 사이트를 쓰고 있는데, 나는 "page"(나는 결코 새로운 글이 필요하지 않다고 생각한다.) 이후에 섹션별로 컨셉 등으로 분류 된 코드를 유지하고 싶다.jQuery가 이벤트에 추가하는 것과 같은 WebSocket.onmessage()에 추가 하시겠습니까?

과 같은 이벤트가 계속 표시 될 수있는 것과 동일한 방식으로 WebSocket.onmessage을 코드와 많이 쪼갤 수 있습니다. $('#someElement')에 계속해서 이벤트가 추가 될 수 있습니다.

WebSocket.onmessage(function(){})으로이 작업을 수행 할 수 있습니까? 그렇다면 어떻게?


some jQuery programmers happily know으로, 이벤트는 처음에 다음 설정할 수있는 JS에서 여러 위치에 추가됩니다. 그것이 js에 관한 가장 좋아하는 것입니다. "주문이있는 한 어디서나 넣을 수 있습니다."능력. 이로 인해 코드 구성이 훨씬 쉬워졌습니다.

WebSockets을 사용하면 실제로는 WebSocket.send()을 사용할 수 있고 실제로 서버에 js 데이터를 포트 할 수 있기 때문에 지금까지는 액션 클라이언트 측이 WebSocket.onmessage() 처리기를 사용하고 있습니다.

onmessage()은 이제 내 페이지를 소유하고 있기 때문에 "로그인 성공"유형 메시지가 표시 될 때 첫 번째 콘텐츠 화면으로 로그인 화면을 페이드 아웃하는 것과 같은 대부분의 주요 동작을 시작합니다.

js에 대한 제한된 이해에 따르면 onmessage() 처리기를 모두 한 곳에서 설정해야합니다. 멀리, 멀리, 멀리, js 변경 한 후에 다른 파일을 스크롤하여 뒤로/탭으로 계속 변경하면 고통을 겪을 수 있습니다.

js의 여러 곳에서 WebSocket.onmessage() 처리기를 어떻게 추가 할 수 있습니까?

+0

, 난 당신이 무엇에 관해 얘기하는지 아무 생각이 없습니다! :) 아마도 조금 더 확장하면 더 좋을 것입니다. – Mehran

+0

나는 당신에게 내가 정확하게 이해할 수 있다고 대답 할 수있는 대답을 줄 것입니다. – Mehran

답변

2

WS 이벤트를 자체적으로 처리 할 래퍼를 만들 수 있습니다. 이 예제를 참조하십시오 CoffeeScript :

class WebSocketConnection 
    constructor: (@url) -> 
    @ws   = new WebSocket(@url) 
    @ws.onmessage = @onMessage 
    @callbacks = [] 

    addCallback: (callback) -> 
    @callbacks.push callback 

    onMessage: (event) => 
    for callback in @callbacks 
     callback.call @, event 

# and now use it 
conn = new WebSocketConnection(url) 
conn.addCallback (event) => 
    console.log event 
4

마지막 질문에 답하십시오;

어떻게 js의 여러 곳에서 onmessage 처리기에 추가 할 수 있습니까?

임의의 수의 처리기 기능을 허용하는 개인 (전역) 이벤트 처리기를 정의 할 수 있습니다. 여기에 예제가 있습니다 :

window.bind: function(name, func, context) { 
    if (typeof this.eventHandlers[name] == "undefined") { 
     this.eventHandlers[name] = [func]; 
     this.eventContexts[name] = [context]; 
    } 
    else { 
     var found = false; 
     for (var index in this.eventHandlers[name]) { 
      if (this.eventHandlers[name][index] == func && this.eventContexts[name][index] == context) { 
       found = true; 
       break; 
      } 
     } 
     if (!found) { 
      this.eventHandlers[name].push(func); 
      this.eventContexts[name].push(context); 
     } 
    } 
} 

window.trigger: function(name, args) { 
    if (typeof this.eventHandlers[name] != "undefined") { 
     for (var index in this.eventHandlers[name]) { 
      var obj = this.eventContexts[name][index]; 
      this.eventHandlers[name][index].apply(obj, [args]); 
     } 
    } 
} 

// === Usage === 

//First you will bind an event handler some where in your code (it could be anywhere since `.bind` method is global). 
window.bind("on new email", function(params) { ... }); 

//Then you need to trigger "on new email" in `onmessage` once appropriate events happen. 
WebSocket.onmessage(function(data) { 
    //Work on data and trigger based on that 
    window.trigger("on new email", { subject: data.subject, email: data.email }); 
}) 

이 코드는 이전에 작업 한 오픈 소스 프로젝트의 일부입니다. 이벤트 이름을 제공하고 처리기에 대한 컨텍스트를 설정할 수 있습니다 (함수 대신 메서드 사용). 그런 다음 소켓의 onmessage 핸들러에서 trigger를 호출 할 수 있습니다. 나는 이것이 당신이 찾고있는 것이기를 바랍니다.

0

이 문제를 해결하기 위해 CoffeeScript 클래스를 생성했습니다. @ Valent 's와 비슷하지만 좀 더 완전한 기능을 제공하므로 공유 할 수 있습니다. 웹 소켓 이벤트에 대해 "on", "off""clear" 메소드를 제공하고 "send""close"에 대한 전달 기능을 제공하므로 소켓을 직접 만질 필요가 거의 없습니다. 실제 WebSocket 객체에 액세스해야한다면 superWebSocket.ws에 도착할 수 있습니다.

편집 : URL 종속 싱글 톤을 생성하기 위해 정적 메서드 getConnection을 추가했습니다.이렇게하면 URL 당 단 하나의 연결 만 있고 2 번째를 만들려고하면 기존의 URL 만 제공합니다. 또한 생성자를 직접 호출하는 사람을 보호합니다.

편집 : JSON에서 소켓을 통해 통신합니다. 나는 문자열이 아닌 문자열에 JSON.stringify을 실행하는 코드를 추가하여 send에 전달하고 처리기를 통해받은 모든 메시지에 JSON.parse을 실행하려고 시도합니다.

superSockets = {} 
class SuperWebSocket 
    @getConnection: (url)-> 
     superSockets[url] ?= new SuperWebSocket url 
     superSockets[url] 

    constructor: (url)-> 
     if arguments.callee.caller != SuperWebSocket.getConnection 
      throw new Error "Calling the SuperWebSocket constructor directly is not allowed. Use SuperWebSocket.getConnection(url)" 
     @ws = new WebSocket url 
     events = ['open', 'close', 'message', 'error'] 
     @handlers = {} 
     events.forEach (event)=> 
      @handlers[event] = [] 
      @ws["on#{event}"] = (message)=> 
       if message? 
        try 
         message = JSON.parse message.data 
        catch error 
       for handler in @handlers[event] 
        handler message 
       null 

    on: (event, handler)=> 
     @handlers[event] ?= [] 
     @handlers[event].push handler 
     this 

    off: (event, handler)=> 
     handlerIndex = @handlers[event].indexOf handler 
     if handlerIndex != -1 
      @handlers[event].splice handlerIndex, 1 
     this 

    clear: (event)=> 
     @handlers[event] = [] 
     this 

    send: (message)=> 
     if typeof(message) != 'string' 
      message = JSON.stringify message 
     @ws.send message 

    close: => @ws.close() 
0

당신은 addEventListener으로 작업을 수행 할 수 있습니다 귀하의 질문에 대답에 관심이있는 사람으로

socket.addEventListener('message', function (event) { 
    console.log('Message from server ', event.data); 
}); 
관련 문제