1

I have an app where I'm dynamically loading content into parts of the page. Sometimes the code has data-bind attributes, which seem to be getting ignored by KnockOutJS.

HTML:

<div data-bind="html: code">
    this text is replaced by the JavaScript
</div>
function AppView() {
    var self = this;

    // This sets the code 
    self.code = ko.observable('<div>this shouldnt show</div>');
    self.stuff = ko.observable('this should show');
}

var app = new AppView();
ko.applyBindings(app);

// Later we override the code.  We're setting an observable, so the app should notice.
app.code('<div data-bind="text: stuff">this shouldnt show either</div>');

Esentially, I need the handlers to be initialized. Do I need to remove all bindings, and reapply?

fiddle

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Looks like you might have to do applybindings all over again. Check this SO answer for a similar problem : http://stackoverflow.com/questions/11066732/knockout-data-bind-on-dynamically-generated-elements – Ravi Y Feb 27 '13 at 05:04

2 Answers2

2

This can be done with knockuot Template binding.

see a working example here in this fiddle

In your case you have to do something like this:

<div data-bind="template: 'myTemplate'>
    this text is replaced by the JavaScript
</div>

<script id="myTemplate" type="text/html">
   <div data-bind="text: stuff">this shouldnt show either</div>
</script>

check if it works.

Maurizio In denmark
  • 4,226
  • 2
  • 30
  • 64
  • Thanks. Sometime between when I asked this an now, I figured out template bindings. I use them a lot in my current products. Good answer :-) – Brigand Jul 08 '13 at 17:34
0

There is no need to remove all binding and reapply.

You can change values in event handlers

<div data-bind="html: code>
this text is replaced by the JavaScript
</div>
<span data-bind="click: changeClicked">Change</span>

//inside the model

 self.changeClicked = function(){
 self.code('<div data-bind="text: stuff">this shouldnt show either</div>');
 }

//You can also access from view model with the use of view model instance

Fiddle

NaveenKumar1410
  • 1,565
  • 14
  • 20
  • 1
    Your fiddle still doesn't give the desired result. Since the OP is inserting a new div, which is data-bound to "stuff", they expect to see `this should show` and not 1this shouldn't show either` – Ravi Y Feb 27 '13 at 04:59