Closed terebentina closed 11 years ago
To add to the above, this is how I currently do it:
RestangularProvider.extendModel('notes', function(note) {
note.save = function() {
if (note._id) {
return note.put();
} else {
return note.post();
}
};
return note;
});
Same for all other models, resulting in a lot of copy&paste of the same code. I'd like do define that save function in a single place for all....
If you need it for all models, you can just use the generic onElemRestangularized
RestangularProvider. setOnElemRestangularized(function(elem, isCollection, what) {
elem.myMethod = function() {};
});
With this, myMethod would be added to ALL elements, either if they're collections or not. You can use isCollection to filter by wether a collection or element is to which you're adding this function and the what
is the route (Notes for example).
With this, you can make it in just one place for all of them :)
Check documentation here: https://github.com/mgonto/restangular#setonelemrestangularized
Ah, ok. I kind of tried to follow the advice of using addElementTransformer and couldn't figure out how to do it with that. And when I tried to look up an example using onElemRestangularized, I couldn't find one. I think the onElemRestangularized docs could use a sentence like "Use this to add your custom methods and properties to elements", or a FAQ/example for onElemRestangularized based on this very issue: how to add a .save() method to all models or something.
You could use the onElemRestangularized for whatever you need. It's called after EVERY element has been restangularized.
Do you need extra help getting it to work?
No, absolutely not, thank you. Once you pointed me in the right direction, everything was a breeze. I just commented to let you know that I found the docs a bit foggy and to offer my suggestion of improvement.
Thanks. Ill update them :).
— Sent from Mailbox for iPhone
On Sun, Sep 29, 2013 at 5:25 AM, Dan Caragea notifications@github.com wrote:
No, absolutely not, thank you. Once you pointed me in the right direction, everything was a breeze.
I just commented to let you know that I found the docs a bit foggy and to offer my suggestion of improvement.
Reply to this email directly or view it on GitHub: https://github.com/mgonto/restangular/issues/313#issuecomment-25316438
Hi,
Is there a way to have something like this:
Where save() is a custom function, defined for all models (not just for notes) which simply does something like the following?
Basically my question is how/where can I define a function like this save()?