Skip to content

Instantly share code, notes, and snippets.

@taiju
Created January 17, 2011 07:23
Show Gist options
  • Save taiju/782589 to your computer and use it in GitHub Desktop.
Save taiju/782589 to your computer and use it in GitHub Desktop.
bodyのid属性またはclass属性でdispatcherする
/* 配列周りのメソッド部分がブラウザ依存コードなので、実際はもうちょっとちゃんと書いた方がいい */
/* もしくはMDCからreduce, forEachのコードを引用する */
var Site = function() {
this.id = document.getElementsByTagName('body')[0].getAttribute('id');
this.classes = document.getElementsByTagName('body')[0].getAttribute('class').split(' ');
this.actions = [];
};
Site.prototype = {
doAction: function() {
var self = this;
this.actions.forEach(function(action) {
if (self.id) {
if (action.id === self.id) action.fn(self);
else if (action.id === 'common') action.fn(self);
}
if (self.classes) {
if (self.classes.reduce(function(x, y) {
return (x === true || x === action.cls || y === action.cls) ? true : false;
})) action.fn(self);
}
if (action.cls === 'common') action.fn(self);
});
},
addAction: function(id, fn, cls) {
this.actions.push({ id: id, fn: fn, cls: cls });
}
};
var alertMyId = function(page) {
alert(page.id);
};
var alertIndex = function() {
alert('トップページです!');
};
var alertSubCategory = function() {
alert('俺たちサブカテゴリー!');
};
var alertCommon = function() {
alert('すべてのページで出ます!');
};
var mysite = new Site();
mysite.addAction('index', alertMyId);
mysite.addAction('index', alertIndex);
mysite.addAction(null, alertSubCategory, 'sub');
mysite.addAction(null, alertCommon, 'common');
mysite.doAction();
/* ついでにCSSファイルでもシグネチャに使えたり */
#index ... {
xxx: ...;
}
body.sub {
xxx: ...;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment