我有一个非常基本的JavaScript代码但我多次重复相同的代码块 作为旁注,我使用ruby作为后端代码。
如何在我的文件example.js
中对其进行分解<% if x= 0 %>
var msg;
msg = Messenger().post({
<% if y = 2 %>
message: 'example',
type: 'error',
hideAfter: 3000
<% elsif y = 3 and z =5%>
message: 'example',
type: 'error',
hideAfter: 3000
<% else %>
message: 'different'
type: 'different'
<% elsif y>2 and y < 7 %>
<% if y = 2 %>
message: 'example',
type: 'error',
hideAfter: 3000
<% elsif y = 3 and z =5%>
message: 'example',
type: 'error',
hideAfter: 3000
<% else %>
message: 'different'
type: 'different'
<% else %>
you're a cool dude
<% end %>
这只是一个例子,但我不知道如何简单地用很短的属性替换大块代码并重新使用它
我认为这是不可能的,但这就是我想要的精神:
CHUNK=
message: 'example',
type: 'error',
hideAfter: 3000
<% if x= 0 %>
var msg;
msg = Messenger().post({
<% if y = 2 %>
CHUNK
<% elsif y = 3 and z =5%>
CHUNK
<% else %>
message: 'different'
type: 'different'
<% elsif y>2 and y < 7 %>
CHUNK
<% elsif y = 3 and z =7%>
soso
<% else %>
CHUNK
<% else %>
you're a cool dude
<% end %>
当您拥有类似的代码块时,是否有可能对代码进行分解,这些代码块会像上面那样重复多次。怎么样?
答案 0 :(得分:1)
它应该是可行的。您的post
函数正在接受一个对象,因此您可以这样做:
var chunkA = {
message: 'example',
type: 'error',
hideAfter: 3000
}
// the rest of your reusable chunks
然后你可以按如下方式调用它:
var msg = Messenger().post(
<% if y = 2 %>
chunkA
<% elsif y = 3 and z=5 %>
chunkB
<% end %>
// etc.
);
编辑:虽然这回答了OP的问题,但解决这个问题的更好方法是将逻辑移到控制器中。有关解释,请参阅B Seven的答案。
答案 1 :(得分:1)
一切皆有可能。此外,删除代码重复通常是个好主意。 DRY是铁路公司的基本原则之一。
但是,您还有两个更严重的问题:
以下是我将如何修复#2。我更喜欢使用早期返回而不是嵌套if/else/elsif
。这段代码将放在一个单独的文件中,也许是一个视图助手。
def message_for y, z
if y == 2
return { message: 'example',
type: 'error',
hideAfter: 3000 }
...
如果您将此方法用于视图,则可以使用
<%= message_for y, z %>
话虽如此,您也可以重复使用chunk
。
<% @chunk = { message: 'example',
type: 'error',
hideAfter: 3000 } %>