Computed properties on Backbone.Model

I wanted to be able to get computed properties on my backbone models. Especially after seeing it done in Emberjs.

I thought, surely someone else has done this before? So my search in Google landed me here on this blog post by kilon

After reading this site, the code made sense but it’s not really a plugin by any means. And it’s still polluting the model.attributes object with functions, which don’t get sent back to an ajax call when the model is synced.

Then I found Backbone.Spark and honestly hated how ugly the code is. I mean why “spark?” Also I think having a getter and setter in 1 shared function is a pretty strong violation of Single Responsibility Principle.

Then I found Backbone.ComputedFields which has much nicer code and I almost used it; except that I am opinionated enough to make my own to follow the Marionette conventions.

Marionette Views have dynamically called functions for triggers, i.e. when some:event is triggered the function onSomeEvent is called if it exists. Following that same mentality, I applied it to get and set camel case functions. It seems many frameworks do camel case functions and snake case database column names. So that’s exactly the convention I followed. I hijack the Backbone.Model class and add functionality, which I will admit is more obtrusive than the Backbone.ComputedFields implementation, but I liked the intrusion enough to do it this way anyway.

Check out on my github repo here: https://github.com/kdocki/backbone.model.computed