Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to bind click handlers to templates in knockoutjs without having a global viewModel?
    primarykey
    data
    text
    <p>I'm very new to KnockoutJs so I'm hoping that there is a well known best practice for this kind of situation that I just haven't been able to find.</p> <p>I have a view model that contains an array of items. I want to display these items using a template. I also want each item to to be able to toggle between view and edit modes in place. I think what fits best with Knockout is to create the relevant function on either the main view model or (probably better) on each item in the array and then bind this function in the template. So I have created this code on my page:</p> <pre><code>&lt;ul data-bind="template: {name: testTemplate, foreach: items}"&gt;&lt;/ul&gt; &lt;script id="testTemplate" type="text/x-jquery-tmpl"&gt; &lt;li&gt; &lt;img src="icon.png" data-bind="click: displayEditView" /&gt; &lt;span data-bind="text: GBPAmount"&gt;&lt;/span&gt; &lt;input type="text" data-bind="value: GBPAmount" /&gt; &lt;/li&gt; &lt;/script&gt; &lt;script&gt; (function() { var viewModel = new TestViewModel(myItems); ko.applyBindings(viewModel); })(); &lt;/script&gt; </code></pre> <p>And this in a separate file:</p> <pre><code>function TestViewModel(itemsJson) { this.items = ko.mapping.fromJS(itemsJson); for(i = 0; i &lt; this.items.length; ++i) { this.items[i].displayEditView = function () { alert("payment function called"); } } this.displayEditView = function () { alert("viewmodel function called"); } }; </code></pre> <p>Due to the environment my JS is running in I can't add anything to the global namespace, hence the annonymous function to create and set up the view model. (There is a namespace that I can add things to if it is necessary.) This restriction seems to break all the examples I've found, which seem to rely on a global viewModel variable.</p> <p>P.S. If there's an approach that fits better with knockoutJS than what I am trying to do please feel free to suggest it!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload