Vinblad
Vinblad

Reputation: 686

Knockout manual subscription does not get triggered

I've just started a project where I'm trying to use knockout for my viewmodel bindings. But I have a problem where I'm not able to get the view model to react to changes (through manual subscription) made in the view on the selectbox.

var viewModel = function() {
   var self = this;
   self.project = ko.observable();
   self.contractBorders = ko.observable();

   self.contractBorders.subscribe(function (newvalue) {
       alert('something changed!');
   });
};

viewModel.load = function() {
var data = {"project":{"name":"Project XYZ",
"number":338,"id":1,"isNew":false},"contractBorders":[{"name":"Border 1 grund","id":1},   
{"name":"Border 2","id":2},{"name":"Border 3","id":3}]}

viewModel.loadView(data);

};
viewModel.loadView = function(data) {
    self.project = ko.mapping.fromJS(data.project);
    self.contractBorders = ko.mapping.fromJS(data.contractBorders);
    ko.applyBindings(viewModel);    
};

viewModel.load();

Im expecting the "self.contractBorders.subscribe" to be executed but it never happens. Im I doing it totally wrong?

I've created a Fiddle to reproduce the problem here

Any help would be appreciated!

/BR Vinblad

Upvotes: 0

Views: 1748

Answers (1)

Ilya
Ilya

Reputation: 29693

You have many little mistakes in binding and viewModel
1)

viewModel.loadView = function(data) {
    viewModel.project = ko.mapping.fromJS(data.project);
    viewModel.contractBorders = ko.mapping.fromJS(data.contractBorders);
    ko.applyBindings(viewModel);    
};  

2)

var viewModel = new function() {  

3)

 <div class="span2">
                <select  

4)

<input type="text" id="name" name="name" data-bind="value: project().name" />

http://jsfiddle.net/6zzSy/22/

Here I add observable value - selectedBorder
http://jsfiddle.net/6zzSy/24/

here I optimize your code
http://jsfiddle.net/6zzSy/25/

Upvotes: 1

Related Questions