淘汰赛:如何从视图模型中引发事件?

时间:2014-11-10 20:48:03

标签: knockout.js

我必须使用一些遗留代码,我需要这个" hack"。我有一个视图模型,我需要这个视图模型来引发一个事件,以便它可以由其他一些javascript模块处理(不是ko绑定)。以下是我目前的解决方案,但我想知道是否有更优雅的解决方案。

var vm = { 
    // I could have used ko.observable().extend({notify:"always"}) here, 
    // but that will require me to pass a dummy value as an arg to raise 
    // an event, which is ugly.
    onDataReceived: new ko.subscribable(), 
    handleSomeButton: function () {  
        // fancy code, fancy code, fancy code
        self.onDataReceived.notifySubscribers();
    }
};

vm.onDataReceived.subscribe(function () {
    // some code that can't be turned into a binding.
    window.alert("Yep, using window.alert to handle VM events, so what?");
});

KO版本:3.1.0

同时 我可以使用$.Callbacks,但我不想为处理事件引入类似但又不同的模式。

0 个答案:

没有答案