[英]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.