2015-11-28 2 views
-3

У меня есть этот огромный блок кода в моем редакторе, который просто выглядит так, как будто это можно сделать лучше.Условная строка - лучший способ?

По существу, в зависимости от значения 'divert_poss' Мне нужно отобразить немного другую строку. «divert_poss» либо 1 или 0, и его значение влияет таблица приблизилась «divert_enabled» и «warning_enabled»

Что является наиболее эффективным способом достижения этой цели? Код ниже работает, но должен быть лучший способ?

if (_store.divert_poss == 1) 
{ 
// show divert info for those where divert_poss=1 
return [ 
    '<div class="medium-4', clearClass, ' column">', 
    '<div class="store-locator__infobox" id="store', index, '">', 
    '<div class="infobox__row infobox__row--marker">', 
    '<div class="infobox__marker', (letter.length > 1) ? ' infobox__marker--small' : '', '">',letter,'</div>', 
    '</div>','<div class="infobox__body">', 
     '<div class="infobox__row infobox__title store-image" style="display:none;">',_store.storeimage,'</div>', 
     '<div id="storeid" class="infobox__row infobox__title store-storeid" style="display:none;">',_store.storeid,'</div>', 
     '<div class="infobox__row infobox__title store-divert_poss" style="display:none;">',_store.divert_poss,'</div>', 
     '<div class="infobox__row infobox__title store-location"><center>',_store.location,'</div>', 
     '<div class="infobox__row store-address" style="display:none;">',_store.address, '</div>', 
     '<div class="infobox__row store-website" style="display:none;"><a target="new" href="http://',_store.website.replace(/(http:\/\/)\1/, '$1'),'">',_store.website, '</a></div>', 
    '<div class="infobox__row store-email" style="display:none;"><a href="mailto:',_store.email,'">',_store.email, '</a></div>', 
    '<div class="infobox__row store-tel" style="display:none;">Tel: ',_store.telephone, '</div>', 
    '<div class="infobox__row store-cat_id" style="text-align: center">',_store.cat_id, '</div>', 
    '<div class="infobox__row store-description" style="display:none;">',_store.description, '</div>', 
    '<div class="infobox__row store-specialism" style="display:none;">',_store.specialism, '</div>', 
    '<div class="infobox__row store-divert_enabled" style="display:none;">', 
    '<table width="100%"><tr><td align="center">Divert Status</td><td align="center">Warning Status</td></tr>', 
    '<tr><td align="center" width="50%">',_store.divert_enabled,'</td></div>', 
    '<div class="infobox__row store-warning_enabled" style="display:none;">', 
    '<td align="center" width="50%">',_store.warning_enabled, '</td></tr></table></div>', 
    '<div class="infobox__row store-embedvideo" style="display:none;">',_store.embedvideo, '</div>', 
    '<div class="infobox__row store-defaultmedia" style="display:none;">',_store.defaultmedia, '</div>', 
    '</div>',getDirections, 
    // '<div style="display:none;">', 
    // getStreetView, 
    // '</div>', 
    '</div>','</div>'].join(''); 
}else 
{ 
// hide divert info for those where divert_poss=0 
return [ 
    '<div class="medium-4', clearClass, ' column">', 
    '<div class="store-locator__infobox" id="store', index, '">', 
    '<div class="infobox__row infobox__row--marker">', 
    '<div class="infobox__marker', (letter.length > 1) ? ' infobox__marker--small' : '', '">',letter,'</div>','</div>', 
    '<div class="infobox__body">','<div class="infobox__row infobox__title store-image" style="display:none;">',_store.storeimage,'</div>', 
    '<div id="storeid" class="infobox__row infobox__title store-storeid" style="display:none;">',_store.storeid,'</div>', 
    '<div class="infobox__row infobox__title store-divert_poss" style="display:none;">',_store.divert_poss,'</div>', 
    '<div class="infobox__row infobox__title store-location"><center>',_store.location,'</div>', 
    '<div class="infobox__row store-address" style="display:none;">',_store.address, '</div>', 
    '<div class="infobox__row store-website" style="display:none;"><a target="new" href="http://',_store.website.replace(/(http:\/\/)\1/, '$1'),'">',_store.website, '</a></div>', 
    '<div class="infobox__row store-email" style="display:none;"><a href="mailto:',_store.email,'">',_store.email, '</a></div>', 
    '<div class="infobox__row store-tel" style="display:none;">Tel: ',_store.telephone, '</div>', 
    '<div class="infobox__row store-cat_id" style="text-align: center">',_store.cat_id, '</div>', 
    '<div class="infobox__row store-description" style="display:none;">',_store.description, '</div>', 
    '<div class="infobox__row store-specialism" style="display:none;">',_store.specialism, '</div>',  
    '<div class="infobox__row store-divert_enabled" style="display:none;"></div>', 
    '<div class="infobox__row store-warning_enabled" style="display:none;"><table width="100%"><tr><td align="center" width="100%">Warning Info</td></tr><tr><td align="center">',_store.warning_enabled, '</td></tr></table></div>', 
    '<div class="infobox__row store-embedvideo" style="display:none;">',_store.embedvideo, '</div>', 
    '<div class="infobox__row store-defaultmedia" style="display:none;">',_store.defaultmedia, '</div>', 
    '</div>',getDirections, 
    // '<div style="display:none;">', 
    // getStreetView, 
    // '</div>', 
    '</div>','</div>'].join(''); 
} 

}

+0

Не можете ли вы просто извлечь из обеих этих строк пересечение и поместить его в переменную, а в if/else просто добавить часть, которая отличается? – PatNowak

+0

Я бы рекомендовал создать массив JSON и передать его в полезный JS-плагин под названием Mustache.js - в основном вы создаете HTML-шаблон и передаете массив в функции init. Также избавьтесь от своего встроенного стиля CSS, он уродливый –

+0

String concatenation - одна из самых дорогих вещей для вычисления, я лично считаю это плохой практикой. Однако я думаю, что это может помочь [join vs concat] (http://stackoverflow.com/questions/7299010/why-is-string-concatenation-faster-than-array-join#7299040) –

ответ

0

Fi и убедитесь, что вы делаете те, которые только меняются. Я мог найти только одну часть, которая меняется.

Похоже, этот бит повторяется на первом:

firstBit = ['<div class="medium-4', clearClass, ' column">', 
'<div class="store-locator__infobox" id="store', index, '">', 
'<div class="infobox__row infobox__row--marker">', 
'<div class="infobox__marker', (letter.length > 1) ? ' infobox__marker--small' : '', '">', letter, '</div>', '</div>', 
'<div class="infobox__body">', '<div class="infobox__row infobox__title store-image" style="display:none;">', _store.storeimage, '</div>', 
'<div id="storeid" class="infobox__row infobox__title store-storeid" style="display:none;">', _store.storeid, '</div>', 
'<div class="infobox__row infobox__title store-divert_poss" style="display:none;">', _store.divert_poss, '</div>', 
'<div class="infobox__row infobox__title store-location"><center>', _store.location, '</div>', 
'<div class="infobox__row store-address" style="display:none;">', _store.address, '</div>', 
'<div class="infobox__row store-website" style="display:none;"><a target="new" href="http://', _store.website.replace(/(http:\/\/)\1/, '$1'), '">', _store.website, '</a></div>', 
'<div class="infobox__row store-email" style="display:none;"><a href="mailto:', _store.email, '">', _store.email, '</a></div>', 
'<div class="infobox__row store-tel" style="display:none;">Tel: ', _store.telephone, '</div>', 
'<div class="infobox__row store-cat_id" style="text-align: center">', _store.cat_id, '</div>', 
'<div class="infobox__row store-description" style="display:none;">', _store.description, '</div>', 
'<div class="infobox__row store-specialism" style="display:none;">', _store.specialism, '</div>', 
'<div class="infobox__row store-divert_enabled" style="display:none;">'].join(); 

lastBit = ['<div class="infobox__row store-embedvideo" style="display:none;">', _store.embedvideo, '</div>', 
    '<div class="infobox__row store-defaultmedia" style="display:none;">', _store.defaultmedia, '</div>', 
    '</div>', getDirections, 
    // '<div style="display:none;">', 
    // getStreetView, 
    // '</div>', 
    '</div>', '</div>' 
].join(''); 

Так держать эти два бита в сторону. Используйте две средние биты здесь:

middleBit1 = [ 
    '<table width="100%"><tr><td align="center">Divert Status</td><td align="center">Warning Status</td></tr>', 
    '<tr><td align="center" width="50%">', _store.divert_enabled, '</td></div>', 
    '<div class="infobox__row store-warning_enabled" style="display:none;">', 
    '<td align="center" width="50%">', _store.warning_enabled, '</td></tr></table></div>' 
].join(); 

middleBit2 = [ 
    '</div>', 
    '<div class="infobox__row store-warning_enabled" style="display:none;"><table width="100%"><tr><td align="center" width="100%">Warning Info</td></tr><tr><td align="center">', _store.warning_enabled, '</td></tr></table></div>' 
].join(); 

Затем с помощью условного оператора слияния и.

return firstBit + ((_store.divert_poss == 1) ? middleBit1 : middleBit2) + lastBit; 
+1

Это дает больше смысла - спасибо –

+0

Lemme знаю, что вы думаете, попробовав его , :) –

+1

гораздо проще следить и адаптироваться дальше - спасибо за то, что нашли время –

0

Использование условного оператора

(_store.divert_poss ? "stringFor1" : "stringFor0") 

Относно многострочные строки в JS: Creating multiline strings in JavaScript

Так что в вашем случае:

var HTML = "<div>\ 
<p>bla bla "+ (_store.divert_poss ? "stringFor1" : "stringFor0") +" foo bar!</p>\ 
</div>"; 
+0

Я подумал об этом, но у меня остались бы два огромных блока кода. Можно ли как-то вложить условный оператор в строку? –

+0

@nick да Ник '' bla bla bla "+ (cond?" True str ":" false str ") +" bla bla bla "' –

Смежные вопросы