0

私はバックボーン、Javascript、jQuery 初心者であり、物事を理解しようとしています。私のバックボーン ビューには、次のメソッドがあります。

    setError: function (selection, text) {
        console.log("set error");
        this.$el.find(selection).html(text);
        this.$el.find(selection).show();
    },

エラーフィールドにデータを入力する別のメソッドからこのメソッドを呼び出し、div に他のメッセージを追加したいと考えています。だから私は次のように setError を呼び出してみます:

     populateErrors: function (sampleErrors) {
       console.log("populateErrors");
        _.each(sampleErrors, function (sample) {
            // Set the error
            this.setError('#sample-error', 'test');
            $('#sample-validation-form').append('<p>testing</p>');
        }, this);
    }

私が理解していないのは、setError を呼び出す方法です。したがって、_.each ステートメントの外で呼び出すと、this.setError を実行できます。この Backbone オブジェクトで setError を呼び出しているので、これは理にかなっています。少なくとも私はそう解釈しています。それが間違っている場合はお知らせください。

しかし、_.eachステートメントでは、最後のパラメーターとしてステートメントをバインドしているので、setErrorの前にthisは必要ないと思いました。thisしかし、それを試してみると、setError is undefined になります。そのため、上記のように試してみましたが、_.each ループの外でthis.setError呼び出したときのように「テスト」出力が得られません。this.setErrorこの例でこの関数コンテキストがどのように機能するかを誰かに説明してもらえますか? 私は完全に混乱しています!前もって感謝します!

4

2 に答える 2

1

3 番目の引数としてオブジェクトを渡す場合foo、次のように言っていthisますfoo

populateErrors: function (sampleErrors) {
    // `this` is the Backbone view here
    this.setError('#sample-error', 'test');

    _.each(sampleErrors, function (sample) {
        // since you passed the view (this) to `each`
        // `this` is the Backbone view here also
        this.setError('#sample-error', 'test');
    }, this);
}
于 2013-04-01T15:32:11.450 に答える