2013-01-08 30 views
2

我有一個模型,我正在填充來自服務器的數據。問題是,當數據最初填充時,我的訂閱正在觸發,我不想要。我只希望訂閱在用戶與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. 
    }); 
} 

回答

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. 
    } 
}); 
+0

我正在使用手動訂閱來啓動Ajax調用。你會建議一種不同的方式? –

+0

在具有'if'的表現方面是無害的。如果用戶通過UI組件執行AJAX調用太容易,我會擔心的。這個可觀察的元素綁定到什麼HTML元素? – jjperezaguinaga

相關問題