最近jQuery UIの$.widgetを、ページを構成するコンポーネントそれぞれを管理するClassとして使ってみた。
そんでまー$.widgetは他のwidgetを継承できるんです。
こんなかんじ。
/*
superHoge widget comes first.
This constructor is $.zudo.superHoge
*/
$.widget('zudo.superHoge', {
_create: function(){
alert('zudoSuperHoge');
}
});
/*
$.zudo.hoge extends $.zudo.superHoge.
Wow how easy isn't this?
*/
$.widget('zudo.hoge', $.zudo.superHoge, {
myMethod: function(){
alert('zudoHoge');
}
});
var superHoge = new $.zudo.superHoge;
superHoge._create(); // zudoSuperHoge
var hoge = new $.zudo.hoge;
hoge._create(); // zudoSuperHoge
hoge.myMethod(); // zudoHoge
でも、あーこれ$.zudo.hogeの中で別に_create定義したい場合、それしちゃうと$.zudo.superHogeの_createを上書きしちゃうからどーすればいいんだ。$.zudo.superHogeの_createも呼びたいんだけどーと思ってたらこんな風にしたらできたっぽい。下の例は、newでインスタンス作ったらoptions.template_containerからelementを作るってのをしている。そんで、$.zudo.hogeは、_createを上書きしていて、その中で$.zudo.superHogeの_createを呼んでる。
$.widget('zudo.superHoge', {
options: {
template_container: '<ul />',
template_child: '<li />'
},
_create: function(){
// if widget was created via $(dom).superHoge(),
// don't make element from template
if(this.element){ return this; }
this.element = $(this.options.template_container);
return this;
},
add: function(val){
$(this.options.template_child)
.text(val)
.appendTo(this.element);
return this;
}
});
$.widget('zudo.hoge', $.zudo.superHoge, {
options: {
_super: $.zudo.superHoge
},
_create: function(){
this.options._super.prototype._create.apply(this, arguments);
this.element.addClass('childUl');
return this;
}
});
$(function(){
/*
create superHoge's instance.
the element would be created in '_create'.
the src is defined in options.
*/
var superHogeInstance = (new $.zudo.superHoge)._create();
superHogeInstance.element.appendTo('body');
superHogeInstance
.add('foo')
.add('bar')
.add('moge');
/*
create hoge's instance.
hoge extends superHoge and
hoge has its own '_create' method.
This method overrides superHoge's '_create',
so using 'apply' to call superHoge's '_create'.
*/
var hogeInstance = (new $.zudo.hoge)._create();
hogeInstance.element.appendTo('body');
hogeInstance
.add('foo')
.add('bar')
.add('moge');
});
なんかcallとかapplyとかようわからなかったけど最近それがなんだかちょっと分かってきた気がする。あと、なんかうまくもうちょいできる気がする。というより$.widget使わなくて良くない?とか思ってきた。
