8

私がやりたいことは非常に単純だと思いますが、それを行う方法がわかりません。モデルの属性の 1 つがイベント ハンドラーにデータを渡す目的で変更されたときに、独自のイベントを発生させたいと考えています (変更が値の増加または減少であったかどうか)。

基本的に、ハンドラーにビューでこれを実行してもらいたい

handler: function(increased) {
   if(increased) {
      alert("the value increased")
   }
   else {
      alert("the value decreased")
   }
}

// ...

this.model.on("change:attr", this.handler, this);
4

3 に答える 3

12

どうぞ: 基本的に をリッスンしchange:myvarます。変更が発生すると、モデルを使用previous()して古い値を取得します。増加したか減少したかに応じて、適切なイベントを発生させます。に示すように、これらのイベントを聞くことができますinitialize()

(function($){

    window.MyModel = Backbone.Model.extend({

        initialize: function () {
            this.on('change:myvar', this.onMyVarChange);
            this.on('increased:myvar', function () {                  
                console.log('Increased');                
            });
            this.on('decreased:myvar', function () {                  
                console.log('Decreased');                
            });
        },

        onMyVarChange: function () {
            if (this.get('myvar') > this.previous('myvar')) {
                this.trigger('increased:myvar');  
            } else {
                this.trigger('decreased:myvar');
            }
        }            
    });

    window.mymodel = new MyModel({myvar: 1});
    mymodel.set({myvar: 2});
    mymodel.set({myvar: 3});
    mymodel.set({myvar: 1});

})(jQuery);​

上記を実行すると、「Increased」、「Increased」、「Decreased」がコンソールに出力されます。

于 2012-02-25T11:58:13.413 に答える
2

見てくださいpreviousAttributes()

次に、以下を比較できます。

If(this.get(attr) > this.previousAttributes()[attr]){
    console.log('bigger');
} else {
    console.log('smaller');
}

これをイベントハンドラーで使用すると、changeすべて設定されます。カスタムトリガーや大量のコードは必要ありません。

編集

これは私のBackbone.Validatorsプロジェクトからのものであり、検証ステップ中に変更されたすべての属性のリストを取得する方法は次のとおりです。

var get_changed_attributes = function(previous, current){
    var changedAttributes = [];
    _(current).each(function(val, key){
        if(!_(previous).has(key)){
            changedAttributes.push(key);
        } else if (!_.isEqual(val, previous[key])){
            changedAttributes.push(key);
        }
    });
    return changedAttributes;
};

を使用しているため、これにはアンダースコア1.3.1が必要_.hasです。アップグレードできない場合でも、簡単に交換できます。あなたの場合、あなたは合格this.previousAttributes()し、this.attributes

于 2012-02-25T12:03:35.353 に答える
0

change イベントをリッスンした後に独自のカスタム イベントを発生させたらどうなるでしょうか。

handler: function(increased) {
   this.model.trigger('my-custom-event', stuff, you, want);
},
myHandler: function(stuff, you, want){
    // Do it...
}
// ...
this.model.on("change:attr", this.handler, this);
this.model.on('my-custom-event, this.myHandler, this);
于 2012-02-25T05:42:44.730 に答える