jashkenas / backbone

Give your JS App some Backbone with Models, Views, Collections, and Events
http://backbonejs.org
MIT License
28.09k stars 5.39k forks source link

The attribute Id has been updated, does the attribute nameId also need to be updated? #4239

Open usernameisregistered opened 4 years ago

usernameisregistered commented 4 years ago

https://github.com/jashkenas/backbone/blob/0b1c2e3fce3156fcb9819b8bbf8885456e4e1055/backbone.js#L519

var hacker = new Backbone.Model({
  name: "name",
 idAttribute: 'nameId',
});
if (this.idAttribute in attrs) this.id = this.get(this.idAttribute); 

The attribute Id has been updated, does the attribute nameId also need to be updated? I don't think it is necessary to update the attribute id, just the nameId

I wonder if you can understand Chinese, but my English is poor

yangzhichina commented 4 years ago

The attribute Id had been updated, because the idAttribute was updated. Not the other way around.

jgonggrijp commented 2 years ago

@usernameisregistered If you console.log(hacker), you will find an object that looks like this:

{
    id: undefined,
    // idAttribute inherited from Backbone.Model.prototype, default 'id'
    attributes: {
        name: 'name',
        idAttribute: 'nameId'
    }
    // more properties
}

You probably meant to do this:

// Define a new type of model which obtains its `id` from the `nameId` attribute.
var Hacker = Backbone.Model.extend({
    idAttribute: 'nameId'
});

// Create a new instance of the above model type.
var hacker = new Hacker({
    nameId: 'name'
});

Now console.log(hacker) will output the following instead:

{
    id 'name',
    idAttribute: 'nameId',
    attributes: {
        nameId: 'name'
    }
    // other properties
}

Does this answer your question?