KnockoutJS subscribe to multiple observables with same callback action

后端 未结 5 1071
遇见更好的自我
遇见更好的自我 2020-12-10 01:53

I\'ve got a model class in KnockoutJS which has multiple values that I\'d like to subscribe to. Each subscription will perform the same task, like so:

funct         


        
5条回答
  •  再見小時候
    2020-12-10 02:19

    You can create some kind of an extension for this purpose. Simple example:

    function subscribeMany(callback, observables) {    
        for (var i = 0; i < observables.length; i++) {
            observables[i].subscribe(callback);
        }
    }
    

    Usage:

    var name = ko.observable();
    var email = ko.observable();
    
    var callback = function(value) {
        console.log(value);
    };
    
    subscribeMany(callback, [name, email]);
    
    name('test 1')
    email('test 2')
    

提交回复
热议问题