How to build nested backbone.js models that can be re-used with different underlying sync methods
-
25-10-2019 - |
Pergunta
I'm building a javascript heavy app that presents two different views to the user. One view is through my own app's web interface, and thus can use a RESTful API to connect, the other is in an OpenSocial gadget (and thus uses the opensocial API to fetch and retrieve data).
What I've done so far is to have a common set of models/views that I can re-use across both the web interface and the opensocial gadget, and use a mixin to replace the sync methods for the opensocial gadget.
eg.
MyBaseModel = Backbone.Model.extend({
... typical backbone model
});
MyOpenSocialMixin = {
sync: function(...) {
// Sync via opensocial here
}
};
myOpenSocialModel = MyBaseModel.extend(MyOpenSocialMixin);
myOpenSocialModel.sync(); // works on opensocial
myAppModel = new MyBaseModel();
myAppModel.sync(); // works on the normal interface
This works great for a single model, but doesn't work for nested models (for example, if MyBaseModel contains a number of MySubModels). What's the best practice for dealing with this situation? Should my nested models inherit the sync() method of their parent? Is there a better design pattern?
Solução
It would certainly be possible, in the constructor of a child class, to pass the parent's SYNC method. If the method is unbound, you can just copy it into the child class the same way Backbone does:
def initialize(attributes, options) {
_.extend(this, {sync: options.parent.sync});
}