上篇大致讲了对源码的理解,这篇展示一个初步的九宫格控件。直接上源码:
webix.protoUI({
name:"grid",
$init:function(config){
config.rowCount = config.rowCount || 3;
config.colCount = config.colCount || 3;
if(!config.rows){
config.rows = [];
}
config.rows.push({
view:"toolbar",
cols:[
{id:config.id+"btn_2",view:"button",value:"2*2",align:"left",width:60,click:this._adjust},
{id:config.id+"btn_3",view:"button",value:"3*3",align:"left",width:60,click:this._adjust},
{id:config.id+"btn_4",view:"button",value:"4*4",align:"left",width:60,click:this._adjust},
{id:config.id+"_i",view:"text",width:60,align:"right"},
{view:"label",label:"*",width:20,align:"center"},
{id:config.id+"_j",view:"text",width:60,align:"right"},
{id:config.id+"btn_adjust",view:"button",value:"OK",align:"left",width:60,click:this._adjust},
{},
]
});
Array.prototype.push.apply(config.rows, this._initRowCol(config));
this._settings = config;
},
_initRowCol:function(config){
var rows = [];
for(var i=0;i<config.rowCount;i++){
rows.push({cols:[]});
for(var j=0;j<config.colCount;j++){
var tmp = webix.clone(config.itemTemplate);
tmp.id = config.id+"_row"+i+"_col"+j;
rows[i].cols.push(tmp);
}
}
return rows;
},
_reconstruct:function(){
this._collection = this._collection.slice(0, 1);
var rowsConfig = this._initRowCol(this._settings);
Array.prototype.push.apply(this._collection, rowsConfig);
webix.ui.baselayout.prototype.reconstruct.call(this);
},
_adjust:function(id,e){
var parent = this._parent_cell._parent_cell;
var count = id.substr(id.lastIndexOf("_")+1);
if(webix.ui.grid.prototype._isNumber.call(parent, count)){
parent._settings.rowCount = parent._settings.colCount = count;
} else {
var id = parent._settings.id;
var i = $$(id+"_i").getValue();
var j = $$(id+"_j").getValue();
if(!webix.ui.grid.prototype._isNumber.call(parent, i) || !webix.ui.grid.prototype._isNumber.call(parent, j)){
webix.message("Please input number");
return;
}
parent._settings.rowCount = i;
parent._settings.colCount = j;
}
webix.ui.grid.prototype._reconstruct.call(parent);
},
_isNumber:function(num){
return !isNaN(parseFloat(num)) && isFinite(num);
},
}, webix.ui.layout);
效果见这里,几个n*n的按钮在本地跑是OK的,在webix提供的这个沙盒里会出错,具体没深究。这个控件只是基于layout,动态调整config,再调用baselayout.reconstruct。可以往2方面深入下去:
- 功能上:加入添加监控、选中当前项、绑定list等
- 实现上:基于view自己处理render和event,这样会对原理了解的更深入,也可以学着自己实现一套简单的前端库。
作者:AlexanderYao
出处:http://alexanderyao.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。