2012-03-13 6 views
2

'Item'이라는 자바 스크립트 클래스가 있습니다. '항목'은 다음과 같이 정의됩니다.자바 스크립트에서 이벤트 발생

function Item() { this.create(); } 
Item.prototype = { 
    create: function() { 
    this.data = { 
     id: getNewID(), 
    } 
    }, 

    save: function() { 
    $.ajax({ 
     url: getBackendUrl(), 
     type: "POST", 
     data: JSON.stringify(this.data), 
     contentType: "application/json", 
     success: save_Succeeded, 
     error: save_Failed 
    }); 
    }, 

    function save_Succeeded(result) { 
    // Signal an event here that other JavaScript code can subscribe to. 
    } 

    function save_Failed(e1, e2, e3) { 
    // Signal an event here that other JavaScript code can subscript to. 
    } 
} 

참고 : 저는 C# 배경에서 온 것입니다. 그래서 내가 성취하고 싶은 것이 가능한 것인지 확신 할 수 없습니다. 하지만 본질적으로, 객체를 만들고, 이벤트 핸들러를 구독하고, 객체를 저장하려고합니다. 예를 들어, 내 코드 전체에서 다음과 같은 작업을 수행합니다.

var i = new Item(); 
i.item_save_succeeded = function() { 
    // Do stuff when the item has successfully saved 
}; 
i.item_save_failed = function() { 
    // Do stuff when the item has failed to save 
}; 
i.save(); // start the save process 

자바 스크립트에서도이 이벤트 기반 방법이 가능합니까? 그렇다면 어떻게? 내가 뭘 놓치고 있니? 애매한 다양한 오류가 계속 발생합니다. 그렇기 때문에 나는 점점 더 멀어지고 있는지 잘 모르겠습니다.

도움 주셔서 감사합니다.

+0

나는'$'을 본다. jQuery를 사용하고 있습니까? – epascarello

+0

@epascarello 그는 $ .ajax()가 전형적인 jQuery 구문이므로 $ this라고 가정합니다. – Bram

답변

3

jQuery를 사용하는 경우 사용자 정의 이벤트 유형에 이벤트 핸들러를 추가 할 수 있습니다. 다음 코드는 the jQuery docs

$('#foo').bind('custom', function(event, param1, param2) { 
    alert(param1 + "\n" + param2); 
}); 
$('#foo').trigger('custom', ['Custom', 'Event']); 

에서 가져옵니다하지만 jQuery를 1.7 bind을 deprecates 때문에, 당신은 지금 on를 사용해야합니다. jQuery docs for on을 참조하십시오.

+1

'on' 설명서 http://api.jquery.com/on/ – MilkyWayJoe

0

100 % 확신 할 수 없으며 JS 프로의 답변을 기대하지만, 여기에 내가 할 일이 있습니다.

아이템 개체 - 구독하려는 기능 중 일부 속성을 노출합니다.

항목을 인스턴스화하면 알림을 보내려는 이벤트에 콜백 기능을 제공 할 수 있습니다. 사실상

save: function() { 
var self = this;  
$.ajax({ 
     url: getBackendUrl(), 
     type: "POST", 
     data: JSON.stringify(this.data), 
     contentType: "application/json", 
     success: function() { if(typeof(self.success) == "function") self.success(); } 
     error: function() { if(typeof(self.fail) == "function") self.fail(); } 
    }); 
    }, 

객체에 콜백 함수를 전달하고 필요한 경우는 직접 전화를하자 : 코드에서는 다음과 같은 일을 할 수 있습니다. 나는 누군가가 이제 더 나은 방법을 제안 할 것이라고 확신한다. :-)

관련 문제