【发布时间】:2015-01-16 17:19:39
【问题描述】:
我的代码有问题,我正在使用 hljs 突出显示我正在使用的代码 sn-ps。我写了一个模板系统,例如一般输入是这样的:
<codeexample params="type: html">
<div style="example_class">Example code</div>
</codeexample>
我的模板解释器:
<template id="codeexample">
<div class="code">
<pre><code data-bind="attr: {class: type}, template: { nodes: $componentTemplateNodes, afterRender: $root.handleCode}, visible: false ">
</code></pre>
</div>
</template>
我的handleCode函数:
this.handleCode = function(element) {
var preCodeTags = $(element).find('pre code');
preCodeTags.each(function(i, block) {
hljs.highlightBlock(block);
block.show(100);
});
}
问题是在模板渲染到我的实际模板之前已经调用了 afterRender 函数,我曾经添加一个console.log($(element).find('pre code'));,结果长度为0。
[prevObject: jQuery.fn.jQuery.init[3], context: undefined, selector:
"pre code", constructor: function, init: function…]
context: undefined
length: 0
函数afterRender 是否应该在渲染过程之后运行?
有没有已知的工作?当我使用 200 毫秒的超时时,它工作正常,但在我看来这是最糟糕的解决方案。
【问题讨论】:
-
请在 jsfiddle 中创建一个 repro!还请在您的问题中包含您的
codeexample组件定义!为什么你使用的是哪个 KO 版本?$componentTemplateNodes还没有正式发布... 3.3版本会包含 -
添加小提琴可能有点困难,因为我在单个页面应用程序上使用 html 导入,其中每个页面都有自己的模板文件。你是对的,我包括 3.3alpha,因为我想使用嵌套组件。
标签: templates knockout.js render highlight.js