简体   繁体   中英

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?

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM