我是 knockoutjs 的新手,我有一个非常基本的问题要问你:
我已经能够成功订阅更改屏幕推特句柄的用户,并成功获取推文并使用 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);
});
});
};
最佳答案
要访问可观察对象的实际值,无论它是否为数组,您都需要包含括号。例如,以下将起作用:
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")
关于javascript - 是否可以记录 KO 可观察数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8673040/