Pregunta

I bound multiple ko viewmodels to different panels in the same page, but when the viewmodels have properties with the same name they seem to lose their binding to their own viewModel like:

var Panel1ViewModel = function Panel1ViewModel() {
    var self = this;

    self.isVisible = ko.observable(false);

    self.change1 = function() {
        self.isVisible(!self.isVisible());
    };
};
ko.applyBindings(Panel1ViewModel(), document.getElementById('panel1'));

var Panel2ViewModel = function Panel1ViewModel() {
    var self = this;

    self.isVisible = ko.observable(false);

    self.change2 = function() {
        self.isVisible(!self.isVisible());
    };
};
ko.applyBindings(Panel2ViewModel(), document.getElementById('panel2'));

To make it more clear I recreated the problem in jsfiddle.

I know I can nest ViewModels with with but the page is big and some content is loaded dynamically so I want to separate it.

Can someone explain me why this is happening and wat a possible solution is?

¿Fue útil?

Solución

You're not initiating your view models correctly. Try it like this:

var Panel1ViewModel = function Panel1ViewModel() {
    var self = this;

    self.isVisible = ko.observable(false);

    self.change1 = function() {
        self.isVisible(!self.isVisible());
    };
};
ko.applyBindings(new Panel1ViewModel(), document.getElementById('panel1'));

var Panel2ViewModel = function Panel1ViewModel() {
    var self = this;

    self.isVisible = ko.observable(false);

    self.change2 = function() {
        self.isVisible(!self.isVisible());
    };
};
ko.applyBindings(new Panel2ViewModel(), document.getElementById('panel2'));

http://jsfiddle.net/XWD96/3/

The difference is that the new operator will create a new object (this inside your view model). So by not having the new, this will point to the window in both view models, therefor causing conflicts.

You can read more about Constructor Functions (new) here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top