Reputation: 23535
There appear to be a number of different ways how to access properties of a Sencha (Touch) model. However, I don't seem to be able to find proper documentation of which is the "correct" way of doing it.
Model creation
var model = Ext.create('MyApp.model.MyModel', {
name: value,
foo: bar,
...
})
Property access
model.get('name')
or model.set('name', newValue)
model.data.name
or model.data.name = newValue
model.raw.name
seems to always return a string no matter what the data type in the model definition is?Upvotes: 2
Views: 869
Reputation: 25001
Let's sort this all out:
get
and set
methods are the intended accessors for model field values.
model.data
is the object that stores the client side model value, that is that have been converted from the data received from the server proxy using the fields configuration (type, convert method, etc.).
model.raw
is the raw data that was received from the server proxy, before it was converted to client side application domain model values. You should avoid using it, or you will tie yourself to your proxy/server.
model['name']
: as you've said, it doesn't work. Don't hope for it to come back (I don't even really understand that it worked at one point).
Now, which one should you use? Clearly, the last two ones are already out of the match.
The model.data
object should give you the expected result in most cases (see bellow), and should give you a marginal performance gain other calling a function.
However, IMO you should always prefer to use the getters and setters, for two reasons.
First, it might happen that someone in your team (or you from the past) decides that the getter/setter is a good point to add some custom logic. In this case, bypassing the accessor by using the data
object directly will also bypass this logic, and yield unpredictable result.
Secondly, getters and setters make it really easier to debug some situations, by making it easy to know from where modifications of the model values are coming. I mean, if one day you were to ask yourself "f**k, why is my model field value changing to this??". If all the code uses the getters, you'll just have to put a breakpoint in there, and you'll catch the culprit hand in bag. On the other hand, if the incriminated code uses the data
object directly, you'll be stuck to do a whole project search for... You can't tell exactly what... data.name =
? data['name'] =
? name:
? etc.
Now that I think about it, there is yet another reason. A deprecated one apparently. But the data
object name used to be customizable using this persistenceProperty
option. So, in some cases, the data
object won't even be available, and code doing model.data.name
instead of model[model.persistenceProperty].name
would crash, plain and simple.
Short answer: use the accessors.
Upvotes: 3