Catalin
Catalin

Reputation: 11721

Jquery knockout - define variables inside templates

I have a knockout template, in which i want to define a local parameter (which is a result of a function), and use it inside the template.

<script type="text/html" id="suggestedEmail-template">
    {{ var customVariable = processResult($data); }}
    <li>
        <span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>
    </li>
</script>

Is it possible?

Upvotes: 4

Views: 5519

Answers (2)

smulz
smulz

Reputation: 47

You can do the following:

<script type="text/html" id="suggestedEmail-template">
    <!-- ko if: customVariable = processResult($data) -->
    <li>
        <span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>
    </li>
    <!-- /ko -->
</script>

Upvotes: 2

Paul Manzotti
Paul Manzotti

Reputation: 5147

This sounds like a job for a computed variable:

Inside your view model:

var self = this;
self.customVariable = ko.computed(function()
{
    return processResult(this);
};

Then in your html:

<span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>

Upvotes: 0

Related Questions