防止手动订阅在初始加载时触发

时间:2013-01-08 22:47:44

标签: javascript knockout.js

我有一个模型,我正在填充来自服务器的数据。问题是,当最初填充该数据时,我的订阅正在解雇,我不想要。我只希望在用户与UI交互时触发订阅。

function ViewModel() {
    var self = this;

    //Populate the object.
    self.request = new Request(data);
    //Subscribe to one of the "properties" so that I can do stuff when the value changes.
    self.request.selectedId.subscribe(function(newValue) {
        //This is firing before the user interacts with the UI.
    });
}

1 个答案:

答案 0 :(得分:2)

通常你不需要手动订阅,但是如果你想保留它们,因为你只需要做一次,你总是可以使用一次触发的标志。

self.initialLoad = true;
self.request.selectedId.subscribe(function(newValue) {
    if(self.initialLoad) self.initialLoad = false
    else {
    //This is firing before the user interacts with the UI.
    }
});