I'm using Backbone.js for the first time, and liking it so far. One thing I can't work out at the moment in dynamic attributes of models. For example, say I have a Person model, and I want to get their full name:
var Person = Backbone.Model.extend({ getFullName: function () { return this.get('firstName') + ' ' + this.get('surname'); } });
Then I could do person.getFullName()
. But I'd like to keep it consistent with the other getters, more like person.get('fullName')
. I don't see how to do that without messily overriding Person#get. Or is that my only option?
This is what I've got so far for the overriding option:
var Person = Backbone.Model.extend({ get: function (attr) { switch (attr) { case 'fullName': return this.get('firstName') + ' ' + this.get('surname'); break; case 'somethingElse': return this.doSomethingClever(); break; default: return Backbone.Model.prototype.get.call(this, attr); } } });
I suppose it's not terrible, but it seems there should be a better way.
js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)
BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.
Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).
Would this be simpler?
var Person = Backbone.Model.extend({ get: function (attr) { if (typeof this[attr] == 'function') { return this[attr](); } return Backbone.Model.prototype.get.call(this, attr); } });
This way you could also override existing attributes with functions. What do you think?
I would think of attributes as the raw materials used by a model to provide answers to callers that ask the questions. I actually don't like having callers know too much about the internal attribute structure. Its an implementation detail. What if this structure changes?
So my answer would be: don't do it.
Create a method as you've done and hide the implementation details. Its much cleaner code and survives implementation changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With