Created
January 17, 2011 07:23
-
-
Save taiju/782589 to your computer and use it in GitHub Desktop.
bodyのid属性またはclass属性でdispatcherする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 配列周りのメソッド部分がブラウザ依存コードなので、実際はもうちょっとちゃんと書いた方がいい */ | |
/* もしくは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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ついでにCSSファイルでもシグネチャに使えたり */ | |
#index ... { | |
xxx: ...; | |
} | |
body.sub { | |
xxx: ...; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment