1

私は Backbone.js の初心者で、単純なビューとモデルのシナリオでスコープの問題に遭遇しています。

単一のデフォルト「スコア」値を持つ単純なモデルを作成しました。また、「スコア」の値をレンダリングするテンプレートと、押すたびにスコアを 1 ずつ増やすボタンを含む単純なビューも作成しました。スコア値が変更されるたびに、ビューはレンダリングを繰り返します。

私はこれを機能させましたが、ある意味では失敗かもしれません。ビュー変数「thisView」に「this」の値をキャッシュしない限り、テンプレートは初回のみレンダリングされます。そうしないと、フォーカスが失われ、レンダリング エラーが発生するようです。これは良い考えですか?または、レンダリングを繰り返し適用することについて何か不足していますか。

アドバイスをありがとう

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <style>
       #view_container{background-color: rgba(12, 5, 11, 0.14);width: 100px;height: 100px;padding: 10px;}
    </style>
</head>
<body>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

<!-- View Template -->
<script type="text/template" id="view-template">
    <div class="profileSpace">
        <p>Score: <%= score %></p>
    </div>
    <button id="increaseScoreButton">Increase Score</button>
</script>

<div id="view_container"></div>

<script type="text/javascript">
(function ($) {


MyModel = Backbone.Model.extend({
    defaults:{
        score:0
    },
    initialize: function(){

    },
    increaseScore: function(){

        //Increase Score by 1

        var currentScore = this.get("score");

        var newScore = currentScore +1;

        this.set({score:newScore});

    }
});

MyView = Backbone.View.extend({

        el: $("#view_container"),

        template: _.template($('#view-template').html()),

        initialize: function(model){

                thisView =this;

                this.model.bind('change', this.render, this);

                this.render();

            },
        events: {

            "click #increaseScoreButton":  "increaseScore"

        },

        increaseScore: function(){

            this.model.increaseScore();

        },
        render: function(){

            var currentScore = thisView.model.get("score");

            var html = thisView.template({"score":currentScore});

            $(thisView.el).html( html );
            return thisView;
        }
    });

myModel = new MyModel;
myApp = new MyView({model:myModel});

})(jQuery);

</script>

</body>
</html>
4

1 に答える 1

1
于 2012-10-16T11:21:12.790 に答える