sandrooco
sandrooco

Reputation: 8756

Knockout: Change observable value

I use a requirejs/crossroads setup.

This is my bootstrapping with some global properties:

ko.applyBindings({
    route: router.currentRoute,
    user: {
        ...
    },
    ...
    loading: ko.observable(false),
    setLoadingState: function(newState) {
        this.loading(newState);
    }
});

When calling the setLoadingState function from components (passed via params), it tells me that loading is not a function/undefined.

What's the correct way of implementing such mechanisms?

Upvotes: 1

Views: 81

Answers (1)

user3297291
user3297291

Reputation: 23397

Note that in your (simplified?) example, you don't need an additional method since it only forwards to loading, which can be called directly.


Either use a class like pattern to make sure this refers to your view model like so:

var MyApp = function(router) {
  this.route = router.currentRoute,
  this.loading = ko.observable(false);
};

MyApp.prototype.setLoadingState = function(newState) {
    this.loading(newState);
};


ko.applyBindings(new MyApp(router));

(you can also use the more modern class syntax)

or, use plain objects via a "factory" function:

var MyApp = function(router) {
  var route = router.currentRoute,
  var loading = ko.observable(false);
  var setLoadingState = function(newState) {
    loading(newState);
  };
  
  // Expose what you want to expose:
  return {
    loading: loading,
    setLoadingState: setLoadingState
  };
};

ko.applyBindings(MyApp(router));

Upvotes: 3

Related Questions