asciidisco / Backbone.Mutators

Backbone plugin to override getters and setters with logic
http://asciidisco.github.com/Backbone.Mutators
228 stars 30 forks source link

`this` differs when in .get() and .toJSON() #13

Closed jamesshannon closed 11 years ago

jamesshannon commented 11 years ago

I'm using the bleeding edge version. With Model#get(), this is the model. When using Model#toJSON(), this is the JSON object.

I did a console.log(this) in the mutator function and the following is the output:

>> TT.groups.at(1).get('title')
child {_queue: Backbone.BlockingQueue, cid: "c6", changed: Object, attributes: Object, _changes: Array[0]…}
<< "title"

>> TT.groups.at(1).toJSON()
Object {id: "PL8TioFHubWFtahrzBCr39Z2xNDDX3zyck", kind: "youtube#playlist", etag: ""eTr3dHIt5_K9qdGtRKL-5XdpiQI/mt4VOVwhB_pxNYU0-WoC0_4Xb8U"", snippet: Object, videosLoaded: true…}
<< Object
eicca commented 11 years ago

Confirmed, I met the same problem. In this case we have some problems with working with this. A stupid workaround would be:

if this instanceof ModelClass
  # for 'get'
else
  # for 'toJSON'
jamesshannon commented 11 years ago

My workaround has been to something like:

var channelTitle = (this.get) ? this.get('channelTitle') : this.channelTitle;
return channelTitle ? channelTitle + ' Videos' : ((this.get) ? this.get('snippet') : this.snippet).title;

My mutator's purpose is to return the channelTitle if it's been specified, otherwise return the snippet title, thus the two lines.

asciidisco commented 11 years ago

Good catch guys. I will try to add the fix this weekend (and release a new version).

Thank you.