我有一個名爲'Item'的JavaScript類。 'Item'的定義如下:在JavaScript中觸發事件
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
這種基於事件的方法甚至可以在JavaScript中使用嗎?如果是這樣,怎麼樣?我錯過了什麼?我不斷收到各種模糊的錯誤。因此,我不確定我是越來越近還是越來越遠。
謝謝你的幫助!
我看到'$'。你在使用jQuery嗎? – epascarello 2012-03-13 17:28:19
@epascarello我認爲他是,因爲.ajax()是典型的jQuery語法。 – Bram 2012-03-13 17:31:58