[英]execute a condition after a bind() event in jQuery / Javascript
[英]Bind an event if condition is true or else execute immediately
有沒有一種已知的模式可以代替這種代碼:
if(condition) {
$(el).on("event", function() {
doSomething();
});
}
else {
doSomething();
}
doSomething
在哪里總是相同的功能?
包起來?
function doBindOrExecute(el, condition, func) {
if(condition) {
$(el).on("event", function() {
func();
});
}
else {
func();
}
}
doBindOrExecute(el, true, function() {
// Do stuff
});
對於可讀性或維護而言,這不是最好的方法,但是您可以 :
if(condition || doSomething()) {
$(el).on("event", function() {
doSomething();
});
}
只要doSomething()
不返回真實值。 但是,將其包裝絕對是一個更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.