pathable / supermodel

Supermodel - Minimal Model Tracking for Backbonejs
http://pathable.github.io/supermodel
MIT License
229 stars 36 forks source link

Multiple model change events #62

Open TheBox193 opened 10 years ago

TheBox193 commented 10 years ago

I noticed that when a listener is in place this.listenTo(this.model, 'change', this.doSomething); and an model is loaded that has a related model inside, the model's 'Changed' event will be fired multiple times. Once for the initial state with the full object, and once for when the related model's id is put in place.

For instance if a Post model were loaded with (assuming proper post->user relation):

{
    "post": {
        "id":5,
        "user": {
            "id":10,
            "name": "Joe",
            "username": "joe123"
        },
        "message": "Hello World!"
    }
}

The 'change' event would fire once with the resulting model containing only {"user_id":10} then fired again once when the model's attributes are added. {"id":5, "user_id":10, "message":"Hello World!"}.

Is there a way to prevent the change event from firing until the model is actually loaded? Currently tasks in an app that listen for model changes currently would need to guess if the model is actually filled / ready.

TheBox193 commented 10 years ago

My thought would be in the SuperModel's replace function instead of using model.set(this.id, other.id); to set the id silently by using Backbone's silent option (marks model as changed, but doesn't fire the change event).

var association_id = {};
association_id[this.id] = other.id;
model.set( association_id , {silent: true} );

Or perhaps the less formal approach by directly modifying the attributes which is very silent.

model.attributes[ this.id ] = other.id