Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active December 5, 2016 13:17
Show Gist options
  • Save simonwoo/59c9d9953d9a5adc6c8e7e62e709e288 to your computer and use it in GitHub Desktop.
Save simonwoo/59c9d9953d9a5adc6c8e7e62e709e288 to your computer and use it in GitHub Desktop.
// 定义一个widget基类: 事件处理(观察者模式),组件生命周期管理
// 模板模式: 在子类中实现具体方法
// UI相关有3个方法组成: renderUI生成相关template, bindUI事件绑定, syncUI样式相关
define(function(){
function Widget(){
// this.handlers = {},
this.boundingBox = null;
}
Widget.prototype = {
// 非常经典的观察则模式实现
on: function(type, handler){
if(typeof this.handlers[type] === 'undefined'){
this.handlers[type] = [];
}
this.handlers[type].push(handler);
return this;
},
fire: function(type, data){
if(this.handlers[type] instanceof Array){
var handlers = this.handlers[type];
for(var i = 0, len = handlers.length; i < len; i++){
handlers[i](data);
}
// this.handlers[type] = []; // 此处有bug,会多次出发alert事件
}
},
// 新增2个方法
render: function(container){
this.renderUI();
this.handlers = {};
this.bindUI();
this.syncUI();
$(container || document.body).append(this.boundingBox);
},
destroy: function(){
this.destructor();
this.boundingBox.off();
this.boundingBox.remove();
},
// 新增4个空接口,需要由具体的子类来实现
renderUI: function(){},
bindUI: function(){},
syncUI: function(){},
destructor: function(){}
}
return{
Widget: Widget
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment