HTML:
<script type="text/html" id="underscoreTemplate">
<% _.each(arr(), function(x) { %>
<button onclick="x.doSomething()"><%= x.label %></button>
<% }) %>
</script>
Knockout.js viewmodel:
setupUnderscoreTemplateEngine();
var vm = {
arr: ko.observableArray([
{
label: "lbl1",
doSomething: function() {
alert("foo");
}
},
{
label: "lbl2",
doSomething: function() {
alert("bar");
}
}
])
};
ko.applyBindings(vm);
function setupUnderscoreTemplateEngine() {
/* ---- Begin integration of Underscore template engine with Knockout. Could go in a separate file of course. ---- */
ko.underscoreTemplateEngine = function () {}
ko.underscoreTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), {
renderTemplateSource: function (templateSource, bindingContext, options) {
// Precompile and cache the templates for efficiency
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
precompiled = _.template("<% with($data) { %> " + templateSource.text() + " <% } %>");
templateSource['data']('precompiled', precompiled);
}
// Run the template and parse its output into an array of DOM elements
var renderedMarkup = precompiled(bindingContext).replace(/\s+/g, " ");
return ko.utils.parseHtmlFragment(renderedMarkup);
},
createJavaScriptEvaluatorBlock: function (script) {
return "<%= " + script + " %>";
}
});
ko.setTemplateEngine(new ko.underscoreTemplateEngine());
/* ---- End integration of Underscore template engine with Knockout ---- */
}
请参阅小提琴:http://jsfiddle.net/ballmenace/RrrMe/
我有一个由underscore.js模板引擎渲染出来的按钮。我正在尝试将按钮上的onclick事件绑定到当前viewmodel上的函数。
是的,我知道我可以使用<button data-bind="click: myfunc">
,但我们在使用大型数据集时遇到了糟糕的表现。
甚至可以“捕获”循环中的当前视图模型并在稍后的onclick事件处理程序中引用它吗?