Backbone.js (model instanceof Model) via Chrome Extension
Posted
by
Leoncelot
on Stack Overflow
See other posts from Stack Overflow
or by Leoncelot
Published on 2012-05-17T18:39:21Z
Indexed on
2012/07/09
21:15 UTC
Read the original article
Hit count: 232
Hey guys,
This is my first time ever posting on this site and the problem I'm about to pose is difficult to articulate due to the set of variables required to arrive at it. Let me just quickly explain the framework I'm working with.
I'm building a Chrome Extension using jQuery, jQuery-ui, and Backbone
The entire JS suite for the extension is written in CoffeeScript and I'm utilizing Rails and the asset pipeline to manage it all. This means that when I want to deploy my extension code I run rake assets:precompile
and copy the resulting compressed JS to my extensions Directory.
The nice thing about this approach is that I can actually run the extension js from inside my Rails app by including the library. This is basically the same as my extensions background.js file which injects the js as a content script.
Anyway, the problem I've recently encountered was when I tried testing my extension on my buddy's site, whiskeynotes.com.
What I was noticing is that my backbone models were being mangled upon adding them to their respective collections. So something like
this.collection.add(new SomeModel)
created some nonsense version of my model.
This code eventually runs into Backbone's prepareModel code
_prepareModel: function(model, options) {
options || (options = {});
if (!(model instanceof Model)) {
var attrs = model;
options.collection = this;
model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) model = false;
} else if (!model.collection) {
model.collection = this;
}
return model;
},
Now, in most of the sites on which I've tested the extension, the result is normal, however on my buddy's site the !(model instance Model)
evaluates to true even though it is actually an instance of the correct class. The consequence is a super messed up version of the model where the model's attributes is a reference to the models collection (strange right?). Needless to say, all kinds of crazy things were happening afterward.
Why this is occurring is beyond me. However changing this line (!(model instanceof Model))
to (!(model instanceof Backbone.Model))
seems to fix the problem. I thought maybe it had something to do with the Flot library (jQuery graph library) creating their own version of 'Model' but looking through the source yielded no instances of it. I'm just curious as to why this would happen. And does it make sense to add this little change to the Backbone source?
Update:
I just realized that the "fix" doesn't actually work. I can also add that my backbone Models are namespaced in a wrapping object so that declaration looks something like class SomeNamespace.SomeModel extends Backbone.Model
© Stack Overflow or respective owner