1

我是新來knockoutjs和我對你的尤伯杯基本問題:是否可以記錄KO可觀察數組?

我已經能夠成功訂閱用戶改變屏幕上的Twitter的手柄,併成功獲取鳴叫和顯示的最後一個最近的鳴叫使用console.log(json.results[0].text);的用戶但是我不確定我的可觀察陣列是否正常工作,當我將json.results插入最近的推文時:recent_tweets.push(json.results[0].text)我看到一個空陣列[]

這是怎麼回事?是否可以記錄ko.observable數組?

console.log("TwitterFeedComponent loaded") 
TwitterFeedComponent = function(attributes) { 
    if (arguments[0] === inheriting) 
    return; 

    console.log("TwitterFeedComponent() loaded") 

    var component = this; 
    var url = 'https://twitter.com/search.json?callback=?'; 

    this.attributes.twitter_user_handle.subscribe(function(value) { 
    alert("the new value of the twitter handle is " + value); 
    console.log("I have loaded") 

    var url = 'https://twitter.com/search.json?callback=?'; 
    var twitter_parameters = { 
     include_entities: true, 
     include_rts: true, 
     q: 'from:' + value, 
     count: '3' 
    } 

    $.getJSON(url,twitter_parameters, 
    function(json) { 
     result = json.results[0].text 
     recent_tweets.push(json.results[0].text); 
     console.log(recent_tweets); 
     console.log(json.results[0].text); 

    }); 

}); 
}; 
+1

您需要記錄底層數組,如'console.log(recent_tweets())' – 2011-12-29 20:41:42

回答

4

要訪問觀察值的實際值,無論它是否爲數組,您需要包括括號。例如,以下內容將起作用:

var recent_tweets= ko.observableArray(["hello", "hi", "how are you"]); 
console.log(recent_tweets()); 

分配變量時也是如此。

這是一個普通的標值的例子:

var myObservableName = ko.observable("Luis"); 
myObservableName("Dany"); // changes the name to: Dany 
var Name = myObservableName(); // gets the value and assigns it to the variable Name (in this case the value is "Dany") 
1

以不同的方式回答這個問題一點,你總是可以使用淘汰賽的訂閱()功能。讓我們假設你有以下視圖模型:

App.MyViewModel = function() { 
    var self = this; 

    self.TestProperty = ko.observable(null); 
} 

爲了演示起見,我們假設這個屬性被綁定到一個文本框,如下所示:

<input type="text" id="TestPropertyField" data-bind="textInput: TestProperty" /> 

現在讓我們假設你想隨時記錄這個值的變化。要做到這一點,只需更新您的視圖模型,如下所示:

App.MyViewModel = function() { 
    var self = this; 

    self.TestProperty = ko.observable(null); 
    self.TestProperty.subscribe(function(newValue){ 
     console.log("The new value is: " + newValue); 
    }); 
}