2013-11-22 17 views
0

以下兩個代碼示例類acomplished自定義事件都給了我在面試,我無法管理,使其工作:

//CODE1: 
var e = new Event(); 

e.on('myevent', function (a, b) { 
    console.log(a + ' ' + b); 
}); 

e.trigger('myevent', ['Hello', 'world']); 


//CODE2: 
e.on('hello', function() { 
    console.log('Hello'); 
    this.trigger('world'); 
}).on('world', function() { 
    console.log('World'); 
}).trigger('hello'); 

所以給出了兩個代碼不能被修改, 調用Event()應該工作,因此兩個代碼示例都會輸出「Hello world」。 現在,我不是要求完整的答案。我並不擅長班級自定義事件 in Javascript。我知道基本知識,但如果你知道我的意思,那麼它還不在我手中。我一直在尋找教程,但我需要某人「smarter」告訴我應該從哪裏開始,爲我的問題提供一些好的教程鏈接。

謝謝!

回答

1

演示http://jsfiddle.net/uAQn9/

代碼:

function Event() { 

} 

Event.prototype = { 

    trigger:function(eventName, arParam) { 
    $(window).trigger(eventName, arParam); 
    }, 

    on: function(eventName, cb) { 
    var event = this; 
    $(window).on(eventName, function(e) { 
     var args = Array.prototype.slice.call(arguments); 
     cb.apply(event, args.slice(1)); 
    }); 
    return this; 
    } 
} 

//CODE1: 
var e = new Event(); 

e.on('myevent', function (a, b) { 
    console.log(a + ' ' + b); 
}); 

e.trigger('myevent', ['Hello', 'world']); 


//CODE2: 
e.on('hello', function() { 
    console.log('Hello'); 
    this.trigger('world'); 
}).on('world', function() { 
    console.log('World'); 
}).trigger('hello'); 
+0

編輯代碼。根據規格創建Event類。 – closure

2

.on()用於將事件綁定到元素。你不能綁定事件,事件,看到的示例代碼:

$('div').on('hello', function() { 
    console.log('Hello'); 
    $(this).trigger('world'); 
}).on('world', function() { 
    console.log('World'); 
}).trigger('hello'); 
+0

你的回答讓我的問題看起來有點小我,但我仍然無法明白,我應該如何實現'Event()類'。 – tormex

+0

您的意思是:'var e = $ .Event(「hello」); $('div')。on(e.type,function(){...});'http://jsfiddle.net/Yhvnx/我不知道我明白你在找什麼 –

+0

我已經更新了我的問題,更具體一些。 – tormex