2

html:

<script type="text/html" id="underscoreTemplate">
    <% _.each(arr(), function(x) { %> 
        <button onclick="x.doSomething()"><%= x.label %></button>
    <% }) %>
</script>

Knockout.js 视图模型:

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 事件绑定到当前视图模型上的函数。

是的,我知道我可以使用<button data-bind="click: myfunc">,但是在大型数据集上使用它时性能很差。

是否有可能在循环中“捕获”当前视图模型并稍后在 onclick 事件处理程序中引用它?

4

0 回答 0