2

I made and initialized my model with the "change:status" event like this

Box = Backbone.Model.extend({
    initialize: function() {
      this.on('change:status', this.changed, this);
    },
    changed: function() {
      $('.changed').text('I changed'); // Testing if the 'change:status' is fired
    }
});

My Box collections is setup this way

BoxList = Backbone.Collection.extend({
    model: Box,
    initialize: function() {
       this.on('add', this.addOne, this);
       socket.on('box-status-change', this.boxStatusChanged, this);
    },
    boxStatusChanged: function(box) {
        Boxes.each(function(model) {
          if(model.get('changed') == box.changed) {
            model.set({status: 'changed'});
          }
        });
    },
    addOne: function.... // Some code removed
});

Boxes = new BoxList();

Checking in Chromes web developer tools, the attribute status was set to changed properly but an error Uncaught TypeError: Object #<Object> has no method 'apply' occured. The change:title event of the model was not fired. Is there something I miss when adding the event to the model?

By the way, I'm using the backbone-iosync.js for the Backbone.sync method...


Backbone uses an internal attribute called changed on models:

http://backbonejs.org/#Model-changed

changed model.changed
The changed property is the internal hash containing all the attributes that have changed since the last "change" event was triggered. Please do not update changed directly. Its state is maintained internally by set and change. A copy of changed can be acquired from changedAttributes.

Rename your callback to something else and that works

Box = Backbone.Model.extend({
    initialize: function() {
      this.on('change:status', this.changedState, this);
    },
    changedState: function() {
      console.log('changed');
    }
});

A Fiddle to reproduce your problem http://jsfiddle.net/NrTPk/ and a modified version http://jsfiddle.net/NrTPk/1/

4

1 に答える 1

4

Backbone は、モデルで changed と呼ばれる内部属性を使用します。

http://backbonejs.org/#モデル変更

changed model.changed
changed プロパティは、最後の「変更」イベントがトリガーされてから変更されたすべての属性を含む内部ハッシュです。変更されたものを直接更新しないでください。その状態は、設定と変更によって内部的に維持されます。changed のコピーは changedAttributes から取得できます。

コールバックの名前を別の名前に変更すると、それが機能します

Box = Backbone.Model.extend({
    initialize: function() {
      this.on('change:status', this.changedState, this);
    },
    changedState: function() {
      console.log('changed');
    }
});

問題を再現するフィドルhttp://jsfiddle.net/NrTPk/および修正版http://jsfiddle.net/NrTPk/1/

于 2012-08-21T10:11:58.330 に答える