Should representations specify model data?

I'm just trying to figure out a possibly simple question.

Should representations specify model data directly or only calls to model methods that modify their own data?

+6
source share
2 answers

like everything else in software development, "it depends."

if you use form inputs in your views, and you just need to get data from these inputs in the model, set the data directly. You can do this in any number of ways, including "changing" events from input fields, for example:

MyView = Backbone.View.extend({ events: { "change #name", "setName" }, setName: function(e){ var val = $(e.currentTarget).val(); this.model.set({name: val}); } }); 

On the other hand, if you are starting a business logic and other code that allows you to set data in a model (but actually it is only done as part of the business logic), you must call the method on the model.

The state machine will be a good example of when you do this. Or, in the image gallery I wrote, I had some logic around choosing an image to display. If an image has already been selected, do not select it again. I applied this logic in the method of my image model:

 Image = Backbone.Model.extend({ select: function(){ if (!this.get("selected")){ this.set({selected: true}); } } }); 

As shown here, I like to work by a simple rule: if I have zero logic around the call for dialing, I install it directly from where I am. If there is any logic associated with the model around the set, then I put it in the model.

In any case, when you want to set the data, you should use the set method. Bypassing this and setting model attributes directly through model.attributes prevent a lot of Backbone code from running and could potentially cause problems for you.

+12
source

It depends on your programming style. I always asked them directly. If the Law of Demeter sounds good to you and you are in object orientation (and possibly with Java / Microsoft -stack backgrounds), then the style will be to create getter / setter methods.

If you, on the other hand, are in the Size is the Enemy camp (I also recommend Jeff Atwood's comments ), you should definitely install these models directly (as I mentioned earlier, I myself am in this camp).

At the same time, Backbone.js models already have getter and setter .get and .set methods. You should not directly manipulate the .attributes element. I am not sure that you should not read, I often do this and have no problems because of this.

+1
source

Source: https://habr.com/ru/post/898498/


All Articles