1

私はknockoutjsの新人です。私はあなたのための基本的な質問があります:KO観測可能な配列を記録することは可能ですか?

オンスクリーントゥウィッターハンドルを変更したユーザーにサブスクリプションを行い、つぶやきを正常に取得して最後の最近のつぶやきを表示できましたconsole.log(json.results[0].text);を使用しているユーザしかし、json.resultsを最近のつぶやきにプッシュすると、観測可能なアレイが動作しているとは確信していません。 []空の配列があります。

何が起こっていますか? 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())'のような基本配列をログに記録する必要があります。 –

答えて

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); 
    }); 
} 
関連する問題