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); 
    }); 
} 
相关问题