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