试图将事件绑定到的 “东西” 名单时,我上周也有类似的问题。我的哲学斗争导致我关于逻辑少自然胡须(和把手)的这样的回答:https://stackoverflow.com/a/4946409/365252
需要注意的是胡子是很重要的 - 设计 - 逻辑少。这是试图完成什么是
加剧
激励开发人员将逻辑与演示分开,即任何使您的演示标记“跳舞”或链接到“仅由标记无法表达的”“事物”应该远离您的模板。
但是回到我们的问题......真实的Eureka当我意识到我的问题不是“我如何将它与标记绑定”时,我立刻意识到了这一点。
我真正的问题是:“有明确涉及的环路和环路的项目之间的逻辑为什么我使用胡子遍历它们在逻辑较少的环境?”
那么拐弯抹角几分钟击败后,你可能想知道我的解决办法是:
这是我虚构的模板:
<h1>Argh these pesky topics!</h1>
{{{#topics}}} <!-- Note the 3 mustaches to avoid html escaping -->
这是我行的模板:
<button>Shiver me timber, I'm rusty ol' {{name}}</button>
然后是逻辑所有与叶奥尔德的Javascript:
/* Important: Assuming you're using jQuery, if not you'll have to convert the render output from a string to a DOM Node first. jQuery is NOT necessary for this to work - I'm just trying to avoid innerHTML hacks */
var topics = [/* whatever topics are,*/],
topicsDOM = document.createDocumentFragment(),
$ = jQuery,
list,
i, t, row;
for (i = 0, t = topics.length; i < t; i++) {
row = $(Mustache.render(yourRowTemplate, topics[i]));
row.on('click', function() {
/* We know exactly what row this is via topics[i] so you can do anything you'd like here */
};
topicsDOM.appendChild(row);
}
/* Now... this bit I'm not very proud of and I'm hoping someone can point out a better solution */
list = $(Mustache.render(yourListTemplate, {
topics: '<ins class="no-collision-please">'}));
/* We're doing this because we want to preserve the decorated DOM Nodes,
Mustache expects plain markup as a string (our <ins>) */
list.find('ins.no-collision-please').replaceWith(topicsDOM);
/* Note that the <ins> never leaves our little sandbox nor does
it cause reflow/layouting since we're working inside a documentFragment (list) */
return list;
和吞咽后,终于这一切库尔急救,明显的回味:我必须这样做绑定的事件,我宁愿只是把<script>
标签我的模板里面!?
如果你问自己这个问题,也许逻辑较少模板不适合你。
声明:我一直在使用Handlebars /胡须不到一个月,我仍然发现自己问上述问题的某些用例。这不是Silver Bullet。
你为什么在2014年使用'onclick'属性? – 2014-09-27 23:44:36