MikeW
MikeW

Reputation: 4809

Knockoutjs - subscribe with mapping plugin

I'm using the knockout mapping plugin, previously I would have set a subscribe like so

self.selectedProduct.subscribe(function (name) {

}
  but I'm unsure of how to do this in this format below. The message I get is

"missing : after property id"

 var viewModel = {

    products: ko.mapping.fromJS([]),
    productOptions: ko.mapping.fromJS([]),
    productOptions.subscribe = function (name) {
        alert('somthing change');
    },
    loadInitialData: function () {
        ko.mapping.fromJS(serverData, viewModel.productOptions);
    }
  }

Upvotes: 4

Views: 2002

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

If you are defining your view model as an object literal, then you can't make a function call like you are doing inline. You would have to do it after your view model is created or create your view model in a different way.

If you did it afterwards, then it would look something like:

  var viewModel = {
    products: ko.mapping.fromJS([]),
    productOptions: ko.mapping.fromJS([]),
    loadInitialData: function () {
        ko.mapping.fromJS(serverData, viewModel.productOptions);
    }
  };

   viewModel.productOptions.subscribe = function (name) {
        alert('somthing change');
   };

If you created your view model using a constructor function, then it would look like:

var ViewModel = function() {
    this.products = ko.mapping.fromJS([]);
    this.productOptions = ko.mapping.fromJS([]);
    this.productOptions.subscribe = function(name) {
         alert("something change");
    };

    this.loadInitialData = function() {
        ko.mapping.fromJS(serverData, this.productOptions);
    };
};


var viewModel = new ViewModel();

Upvotes: 6

Related Questions