Proper way to execute a script tag in a Knockout HTML template

坚强是说给别人听的谎言 提交于 2019-12-13 20:12:16

问题


I have the simple html page, where simple ul list defined with following viewmodel for it:

<div class="row">
  <div class="col-md-6">
    <button class="btn btn-link" data-bind="click: addItem">Add item</button>
    <ul data-bind="foreach: listItems">
      <li>
        <p data-bind="text: itemText"></p>
        <script>
          $(document)
            .ready(function() {
              console.log("new li has added");
            });
        </script>
      </li>
    </ul>
  </div>
  <div class="col-md-6">
    <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
  </div>
</div>
<script>
  function ItemViewModel(text) {
    var self = this;

    self.itemText = ko.observable(text || "");
  }
  function ListViewModel() {
    var self = this;

    self.listItems = ko.observableArray([]);
    self.addItem = function () {
      self.listItems.push(new ItemViewModel("new item: " + self.listItems().length));
    };
  }

  ko.applyBindings(new ListViewModel());
</script>

My fiddle: https://jsfiddle.net/1c3prhhv/

Adding items to list work perfectly, though script tag in list item template doesn't work. Each time when item adds to list, I need to execute all JavaScript code in corresponding script tag.

How to properly add items to Knockout's observable array with executing JavaScript code in them?

来源:https://stackoverflow.com/questions/40400887/proper-way-to-execute-a-script-tag-in-a-knockout-html-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!