Created
January 18, 2017 11:10
-
-
Save wgkoro/b8ac6c1d8d7ce6c23989d83c981df818 to your computer and use it in GitHub Desktop.
Railsで特定のページでだけ動かしたい場合のjs判定
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
// 外部に露出させるオブジェクトを生成 | |
(function(window) { | |
var app = function() {}; | |
// 動作対象ページか判定する。controller名、action名で判定する | |
// どちらか片方指定, 両方指定どちらでも可。 | |
app.prototype.isTargetPage = function(targetHash) { | |
if (!this.hasValidArgument(targetHash)) { | |
return false; | |
} | |
var controllers = this.createTargetArray(targetHash.controller), | |
actions = this.createTargetArray(targetHash.action); | |
var hasController = this.hasTarget('controller', controllers), | |
hasAction = this.hasTarget('action', actions); | |
if (controllers && actions) { | |
if (hasController && hasAction) { | |
return true; | |
} | |
return false; | |
} | |
if (controllers && hasController) { | |
return true; | |
} | |
if (actions && hasAction) { | |
return true; | |
} | |
return false; | |
}; | |
app.prototype.hasTarget = function (attrName, targets) { | |
if (_.isEmpty(targets)) { | |
return false; | |
} | |
var _self = this, | |
result = false; | |
_.forEach(targets, function(v) { | |
if (_self.hasTargetDataAtrr(attrName, v)) { | |
result = true; | |
} | |
}); | |
return result; | |
}; | |
app.prototype.createTargetArray = function(target) { | |
if (_.isEmpty(target)) { | |
return null; | |
} | |
if (_.isArray(target)) { | |
return target; | |
} | |
if (typeof target == 'string') { | |
return [target]; | |
} | |
return null; | |
}; | |
app.prototype.hasValidArgument = function(targetHash) { | |
var warn = function() { | |
console.warn('TargetHash should contain "controller", or "action"'); | |
}; | |
if (_.isEmpty(targetHash.controller) && _.isEmpty(targetHash.action)) { | |
warn(); | |
return false; | |
} | |
return true; | |
}; | |
app.prototype.hasTargetDataAtrr = function(attrName, value) { | |
var selector = '[data-%a="%v"]'.replace('%a', attrName).replace('%v', value); | |
if ($(selector).size() > 0) { | |
return true; | |
} | |
return false; | |
}; | |
window.global = new app(); | |
})(window); | |
/* | |
下記のようにして使う | |
(function(window) { | |
if (!window.global.isTargetPage({ controller : 'dishes', action : ['new', 'edit']})) { return; } | |
// このページでだけ実行したい処理 | |
// : | |
})(window); | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment