-1

I have several HTML pages which I transform into blocks HTML in order to inject them in my main container. However, I have to use the knockout binding because ko.applyBindings (viewModel).

Does not work anymore if i change with jQuery $('container').html(...)?

Here is my code:

var viewModel = {
    appView: {
        Html: ko.observableArray()
    }
}


 this.loadHtmlToPage = function (htmlblock) {
    var contentPage = function (status) {
        this.chain = ko.observable(status);
    }

    viewModel.appView.Html.push(new contentPage(htmlblock));
 }


<div id="container" data-bind="html: chain"></div>
Jayveer Parmar
  • 500
  • 7
  • 25
  • You should not be using jQuery to manipulate the DOM. You should be assigning new values to chain, which is what contains the html that will appear in `div#container`. What you are doing with `chain` does not make sense to me, and I don't understand how `appView.Html` is supposed to fit into the scheme. – Roy J Aug 17 '17 at 19:20
  • This is because I want only one modelView in my application, and I wrap them with sub-objects like dataView, securityView, appView, and so on. It work great, but I cant figure it out with the html binding... – Rulio Jones Aug 17 '17 at 19:34
  • Do you expect to have Knockout bindings in the HTML? – Roy J Aug 17 '17 at 22:10

2 Answers2

1

One thing that is obvious to me is that you're setting chain to be a new observable every time you assign to it. To give an observable new contents, you pass them as an argument.

Declare chain in your viewModel, and then do this.chain(status) to change its contents. Those contents will become the new HTML in your div#container.

var viewModel = {
  appView: {
    Html: ko.observableArray()
  },
  chain: ko.observable()
}

this.loadHtmlToPage = function(htmlblock) {
  var contentPage = function(status) {
    this.chain(status);
  }

  viewModel.appView.Html.push(new contentPage(htmlblock));
}
Roy J
  • 42,522
  • 10
  • 78
  • 102
0
ko.cleanNode($("#conteneur")[0]);
$("#conteneur").html('chaine');
ko.applyBindings(viewModel, $("#conteneur")[0]);
  • **From Review**: This answer was flagged as **low quality**. While answers are always appreciated, it really helps to provide some information about how your code solves the problem at hand. Not everyone may be familiar with your exact coding logic, but may understand your general *approach* or *concept*. To help improve your answer, please provide some [**context surrounding it**](https://meta.stackexchange.com/questions/114762), and see the help article on [**writing great answers**](http://stackoverflow.com/help/how-to-answer) for some tips on how to make your answers count :) – Obsidian Age Aug 17 '17 at 22:46
  • `cleanNode` is the [wrong way](https://stackoverflow.com/a/27453338/392102) to do things. See [the template binding](http://knockoutjs.com/documentation/template-binding.html) instead. – Roy J Aug 18 '17 at 00:15