1

With this code I can test wether a dom node is already bound with knockout.

I should check this before I apply the binding a 2nd time like:

if(!isBound) call applybinding...

Is this really how I should do it?

Is there no cleaner way and why is the framework not handling this for me?

var isBound = function() {
   return !!ko.dataFor(document.getElementById("orderView")));   
};


var app = sammy(function () {

            this.get('#/orders', function () {                

                var ovm = new OrderViewModel();
                ko.applyBindings(ovm , document.getElementById('orderView'));

            });

            this.get('#/customers', function () {

                var cvm = new CustomerViewModel();
                ko.applyBindings(cvm , document.getElementById('responseView'));

            });

        });
bastienne
  • 173
  • 3
  • 8
  • Why would you ever apply a binding more than once? Use a template binding inside the container of `orderView` and `responseView` and change that based on the route – Benjamin Gruenbaum Jul 18 '13 at 11:04
  • because I will visit the same url more than once and there is the applyBinding called. – bastienne Jul 18 '13 at 11:14

3 Answers3

1

Knockoutjs version 2.3.0 will throw an exception (You cannot apply bindings multiple times to the same element.) when bindings are applied more than once, so you could just add an try-catch:

try {
   ko.applyBindings(ovm, document.getElementById('orderView'));
} 
catch(e) {
}       

Knockoutjs uses this statement to check if an element is already bound, but this is not externally exposed:

var alreadyBound = ko.utils.domData.get(node, "__ko_boundElement");
mhu
  • 17,720
  • 10
  • 62
  • 93
1

You can simply remove bindings from the element before you applying your bindings

this.get('#/orders', function () {                

   var ovm = new OrderViewModel(),
       element = document.getElementById('orderView');
   ko.cleanNode(element);
   ko.applyBindings(ovm , element);

});
Dima Kuzmich
  • 1,286
  • 11
  • 18
  • Ok. So maybe it is a good idea to use templates. Another way to do it is explained here https://groups.google.com/forum/#!topic/knockoutjs/HPOWu4PA02c – Dima Kuzmich Jul 18 '13 at 12:36
0

You should call applybindings only once and not work around the exception that knockout is throwing.

When calls are made to order or customer, you should update the data in the view model and the view will automatically update. This is the point of using MVVM.

The MVVM pattern means we have properties which tell the view to update when the data changes, therefore poke new data into your observable properties and the view will update.

I'd be tempted to compose a viewModel of customer and order objects therefore applyBindings can be called on the whole document once. It's generally lead to cleaner code for me.

Captain John
  • 1,859
  • 2
  • 16
  • 30