使用jQuery附加渲染Knockout值

时间:2015-09-23 04:08:12

标签: javascript jquery knockout.js

我正在尝试在jQuery append中渲染Knockout,但似乎该值无法呈现。我需要帮助将html中显示的div呈现到jQuery追加容器中。



var employees = [
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName": "Jones"}
];

var ViewModel = function() {
  var self = this;
  self.LoadMore = ko.observableArray([]);
  self.OnLoadMoreClick = function() { 
  $.ajax({
    $.each(employees, function(index,value) {
       self.LoadMore.push(value);
    });
  
    $.each(employees, function(index,value) {
       var container = '';
       $('#LoadMoreContainer').append(container);
    });
  });
  }
}

ko.applyBindings(new ViewModel());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="LoadMoreContainer">
  <!-- How to move this part into jquery append?
  <!-- ko forEach: LoadMore -->
  <div><div data-bind="firstName"></div><div data-bind="lastName"></div></div>
  <!-- /ko -->
</div>

<div data-bind="click: OnLoadMoreClick">Load More</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

不要这样做!不要自己添加DOM元素。

Knockout是一个MVVM框架,它可以让View(= DOM)与您的视图模型保持同步。 希望控制DOM。如果您使用Knockout,请尝试使用尽可能少的jQuery。对于任何DOM操作几乎完全避免它,除非它真的被警告(例如文档说它没关系)。

(典型的例外情况包括,您只能在custom bindings中自己操纵DOM(明确表示这一点),pre- or post-rendering of foreach bindings或偶尔在the event binding中。)

但是,再次,如果你可以帮助它:不要这样做

相反,将项目添加到observableArray,然后让 Knockout 相应地更新您的视图模型:

&#13;
&#13;
var employees = [
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName": "Jones"}
];

var ViewModel = function() {
  var self = this;
  
  self.LoadMore = ko.observableArray([]);
  
  self.OnLoadMoreClick = function() { 
    $.each(employees, function(index, value) {
      self.LoadMore.push(value);
    });
  }
}

ko.applyBindings(new ViewModel());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="LoadMoreContainer">
  <!-- ko foreach: LoadMore -->
  <div><span data-bind="text: firstName"></span> <span data-bind="text: lastName"></span></div>
  <!-- /ko -->
</div>

<button data-bind="click: OnLoadMoreClick">Load More</button>
&#13;
&#13;
&#13;