简体   繁体   English

淘汰赛:改变可观察的价值

[英]Knockout: Change observable value

I use a requirejs/crossroads setup. 我使用requirejs / crossroads设置。

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 . 当从组件调用setLoadingState函数(通过params传递)时,它告诉我loading不是函数/ 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. 请注意,在您的(简化?)示例中,您不需要其他方法,因为它只转发到loading ,可以直接调用。


Either use a class like pattern to make sure this refers to your view model like so: 使用类似模式的类来确保this引用您的视图模型,如下所示:

 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) (您也可以使用更现代的class语法)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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