[英]Custom event acomplished in Class
以下兩個代碼示例是在求職面試中提供給我的,我無法使其正常工作:
//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”。 現在,我不要求完整的答案。 我不太擅長Java語言中的類和自定義事件 。 我知道基本知識,但是如果您知道我的意思,那還不是我真正掌握的知識。 我一直在尋找教程,但是我需要一個“ 更聰明 ”的人來告訴我應該從哪里開始,也許會為我的問題提供一些好的教程的鏈接。
謝謝!
.on()用於將事件綁定到元素。 您無法將事件綁定到事件,請參見示例代碼:
$('div').on('hello', function() {
console.log('Hello');
$(this).trigger('world');
}).on('world', function() {
console.log('World');
}).trigger('hello');
碼:
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.