简体   繁体   中英

Backbone.js model.get() returning 'undefined' even though I can see the attributes in console.log

I have a model instance, which I set another model instance on, ie model.set('rsvp', new App.Rsvp) .

When I iterate over the collection to generate the list of them in the view, I get undefined when calling model.rsvp.get('attending') .

Yet when I do a console.log(model.rsvp) I get this:

Rsvp
_changing: false
_escapedAttributes: Object
_moreChanges: false
_previousAttributes: Object
_setting: false
attributes: Object
    attending: true
    created_at: "2012-03-28T09:42:22-05:00"
    event_id: 20
    id: 12
    updated_at: "2012-03-28T09:42:22-05:00"
    user_id: 3
__proto__: Object
cid: "c53"
id: 12
__proto__: Rsvp

So it would appear that there is no issue with the object, yet the get returns undefined.

I must admit my Javascript skill is still pretty weak. What am I missing here?

console.log( Object ) can cheat you. It won't show you the state of the Object in the moment of calling console.log .

Check this jsFiddle and open the console. You see how the console.log shows you the state of the Object at the end of the script and not in the moment of the console.log call.

For more reliable info call console.log with simpler values.

(tested is Chrome, Firefox and Safari over OSX)

Read this for more detailed information: Backbone.js Empty Array Attribute

In theory what you are doing should work, but it's probably not a good idea to bypass attributes and store properties directly on model instances. Here's a jsfiddle that shows it works in concept . My guess is that your model instance is getting recreated from source data via fetch somewhere else in your code so the model.rsvp property disappears. That or model is not the same instance you think it is.

model.rsvp = foo; (lets call this code bit #1) which is equivalently model['rsvp'] = foo; is not the same as model.set({'rsvp':foo}); (code bit #2). If you want to tack another model instance foo (or some other object or value) onto a model instance model , use the code bit #1 or its equivalent. If you want to add an attribute value pair to a model instance that might eventually be permanently stored somewhere, use the code bit #2. Likewise, you're only going to have model.rsvp defined if you used model.rsvp = foo; or model['rsvp'] = foo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM