Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout multiple viewmodels with same name variables conflict?

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?

like image 261
Justin Avatar asked Sep 17 '26 16:09

Justin


1 Answers

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)

like image 51
sroes Avatar answered Sep 19 '26 04:09

sroes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!