Do I need a view for every element in backbone - javascript

I have up to 63 elements that get updated when one changes, do I need a View for each one?
What is the correct way to handle this?
I have a tree structure in my html, where nodes are related to other nodes at different levels.
I wrote js code to handle checking and updating, but that was pre-backbone. I can write the code, I just don't know if I need a different view for each element and what the best practice is.

Each view in Backbone is an abstraction of an visual interface unit, backed by business data(model/collection). Wrapping each responsive element as a view is possible, but rarely the best decision, for that generally means the granularity of abstraction is too fine, which may cause the degradation of efficiency and maintainability.
To effectively benefit from Backbone, designer should think in a big picture first. Many people tend to design/write static HTML code first, then inject dynamic JavaScript later. I don't think that's a good approach. It's better to partition your complex system into several relatively simple and well-defined modules, wrapping visual parts into views and business data parts into models/collections. As for DOM elements, they are just (views') implementation details and will naturally follow the definition of views.
To sum up, rather than decide how to map pre-existing DOM elements with views, decide how to implement pre-designed views with DOM elements.

Related

Why DOM manipulation is not preferred in service in AngularJs?

I know it is bad practice to have the DOM manipulation in anywhere other than directive. but I do not understand why is it a bad practice to have the DOM manipulation in the service/factory as we can reuse them.
I have searched online and also found the same question on stackoverflow
stackoverflow question
but still not clear with the answers.
Angular follows declarative principle which means
a style of building the structure and elements of computer
programs—that expresses the logic of a computation without describing
its control flow
At the same time services in angular were introduced to contain business logic. If business flow is complex - imperative approach suites better.
In such a way if you have DOM manipulation in the service you probably violate separation of concerns principle, as you are coupling UI and business layers. And coupling itself eventually ends up in spagetti-code when this "reusable" components (according to new requirements) should look a bit different in the modules where they were integrated
Directives, by definition, are always attached to a DOM node. So when we create a directive, it either expands or replaces the DOM node.
services are engaged with directives so we are able to manipulate view of an app through directives. however, there are cases where you might need to manipulate DOM element(s) via a service, like in a modal window.
I have a rule of thumb for situations like this. can DOM manipulation be done directly with the attached node? and answer to this question tells me if I need to use a directive (yes) or a service (no) but overall it depends on complexity of your project as well.

Design Approach to Marionette Behaviors

We initially approached Marionette Behaviors as a tool to build modular components for our views but that's the thing - only to create behaviors for re-usability. There are still specific behaviors I would like to build in order to separate the view from event driven behaviors however, they would be considered too specific ie. events driven behaviors on a form that interacts with a complex template with complex business logic.
But looking past my situation, is building only modular behaviors the right path? Apparently, Marionette gives the users the freedom to use behaviors as they see fit but should we build a behavior even if its used only once?
Marionette behaviors are a way to extract reusable behavior from a view and then reuse it where needed, just like The Pax Bisonica writes. Although there are definitely good reasons for choosing to abstract your functionality into behaviors even if they will not be reused in other views, instead of building specific non-reusable views or to simply inherit view C from view B, and view B from view A etc.
As an example, let's say we want to have a custom view (C), acting very specifically. That view has x things in common with two other views, so we'll create a new view (B), based on a BaseView class (A), that has the common behavior. Then extend that view to create the custom view we were after (C).
This 'class' inheritance can get quite messy especially as the app grows. Behaviors let's you abstract the functionality to attachable objects instead. With the class inheritance approach, we would have only one initialize method, so if our behavior needs to add listeners etc. in the initialize method then we'd have to change the view right from the beginning.
A behavior is a specific purpose compartmentized which is generally a good way to go, whether you will reuse it later or not, because it's easier to understand, refactor and read.
So yes - I'd recommend you to use behaviors as much as you feel makes sense, even if the behaviors will turn out quite specific and in the end will not need to be reused, if only to keep your views leaner.

Showing modals: Angular directive/libraries VS direct native jQuery/bootstrap calls

I’ve been searching for the best way to handle modals in angular and I'm getting the impression that they need to be separated from controllers in order to achieve separation of concerns in MVC.
However when it comes to implementing this using a directive or a library out there I don't see the need for such massive overhead of adding so much code. Effectively it seems as though we are doing exactly the same thing but with more calls and events kicking off as compared to directly showing a bootstrap modal in the controller or service using jQuery as easy as:
$scope.saveChanges = function () {
$('#messageTitle').text('Done');
$('#messageText').text('Changes have been saved.');
$('#message').modal()
}
Porting a directive to handle the dialog is in effect showing the modal with additional steps and setups between dependencies etc. within angular, external libraries and/or custom code (whichever way it is applied). It's really like having a more simplified method call to a utilities method in some utils file that will just show the modal using jQuery. Again, I would be enlightened to know why this is not case which I expect from more experienced angular experts.
Apart from the fact that it is assumed a correct working way to do it, is there a reason why the DOM should not be referenced inside a controller. Could it have an effect on things like i.e. performance, buggy code, testing etc.?
I know that because it makes test cases easier is one of the reasons. Again, a valid reason however testing is not much of an issue having the DOM in business logic as in the code above if tested right. If there are, even more pressing cases for this, what are they? If any what is the best and most efficient way to achieve separation of the DOM from controllers/services if the same applies to services?
Background into current explanations:
What's the correct way to trigger jQuery DOM Manipulation from within a controller?
Separating DOM manipulation from Angular controllers - Best Practice wanted
AngularJS - why manipulating DOM in controller is a bad thing?
Why is it considered a bad idea to manipulate DOM in controllers?
From my understanding, these are the main reasons why a controller should not manipulate the DOM:
Testing. Test cases or test steps can be made well-structured and very easily testable when testing logic in controllers. Here what is tested is truly what a controller should be responsible for (Model manipulation).
Applying well-structured MVC code at the angular code base. Separation of concerns again gives a plus mark for testing but also makes code more manageable and well structured.
I would be happy to hear more detailed alternative answers to completely confirm and explain that any DOM manipulation what so ever is a bad thing within a controller. On the contrary it would be interesting to know whether there are exceptions. For the information of others and my attempt to answer, the reasons above are the most commonly known reasons and thus probably the only reasons to my knowledge, which fair enough are acceptable reasons at this point.

AngularJS - why manipulating DOM in controller is a bad thing?

Its common knowledge that DOM manipulations should not be performed in AngularJS Controller, its very hard however to find why exactly is it a bad thing. All the sources say its difficult to test and because controller should be used for communication between directives, but fail to illustrate with code why this is a bad thing.
From my understanding I would think that controller, unlike directive, is not associated with any specific HTML, hence all the DOM modifications controller would do would very possibly fail. This would sure complicate development and testing.
Controller in directives being executed before link functions of child directives would also fail as the controller might not be aware of what the actual HTML of the child directives is. Link is executed after controller function and might modify HTML structure.
I hope I make sense here and if someone could clarify why manipulating DOM from controller is a bad thing, maybe some code exampleor link that explains it well that would be great.
The reason it is more difficult to prove their point with a code sample is that the reason can't really be represented by a short code snippet (short enough for Stack Overflow). It is really a maintainability precaution. Over the long term, you want to be able to independently alter the logic behind controllers and views independently, because otherwise a coupled controller and view pair tend to stay that way and limit each other in their ability to change their functionality without breaking the other. As soon as you decide to change anything about the view, you have the chance of making your controller code break without even touching it.
Testing becomes easier over time because the more tests you have, the more you wish that things were more modular and dependent on as little variables and parameters as possible.
Again, it is maintenance that drives this suggestion. The problems listed above might not be that bad starting out. But imagine adopting a project that you didn't build from the ground up and know all the intricacies behind the coupling between controller and view that hold this application together. What if your application reaches so many thousands of lines of code that it would be impossible for you to know all these intricacies even if you DID build it from the ground up?
For a more general understanding of why design patterns like the one you have alluded to are necessary, you can refer to this google search that will take you on a journey as long as you are willing to take. And for a general understanding of why design patterns even exist and why many people end up suggesting the same thing over and over again, you can refer to one of the catalysts to the introduction of design patterns, Christopher Alexander. He shows us that patterns are what they are because they work well and people repeat what works well.
If you look at the ever so popular question "Thinking in AngularJS" if I have a jQuery background? you will get some hints.
One of the biggest factor that i think DOM manipulation is neither needs nor done is because Angular uses declarative approach when it comes to DOM linking as against the imperative approach that you would use with direct DOM manipulation. Some of the answers detail this difference between declarative and imperative approach.
With jQuery you tell the DOM what needs to happen, step by step. With
AngularJS you describe what results you want but not how to do it.
More on this here. Also, check out Mark Rajcok's answer.
A more comprehensive treatment of this topic is also available here What is the difference between declarative and imperative programming
With such an approach the controller implementation is simplified, and we start to get real value as code base size grows and complexity increases.
My perspective is bit different and covers more than testing. It is the ability of the designer to have control over the HTML layout that otherwise would be taken over by writing code inside of the Angular Controller. Consider the following snippet (it is just a simple example)
<div ng-repeat="article in articles">
<p class="article-body">{{article.text}}</p>
</div>
This example just iterates over a collection and prints article in a separate paragraph tag. While it is certainly possible to loop over the collection in an Angular Controller and dynamically generate paragraph tags with text inside it. It will take away designer's capability to modify look & feel. Hence, If there is a requirement to show the article title, instead of doing this
<div ng-repeat="article in articles">
<span class="article-title">{{article.title}}</span>
<p class="article-body">{{article.text}}</p>
</div>
the designer will now have to locate Angular Controller code to modify DOM manipulation. Just compare above two approaches and guess which one will provide more flexibility.

refactoring javascript. decouple markup or separate modules

I'm trying to make a large (~10K lines) javascript code base more maintainable. Pretty much all of the code is contained in one massive class. I want to do some refactoring, but I don't want to completely rewrite the code.
I have two ideas for how to re-organize the code, but I'm not sure which one is best. (I'm very open to other ideas too) What do you think about each of these approaches? How would you decide which is best?
Idea 1 – Decouple markup from business logic.
We have a somewhat complicated set of rules for what and how things should be displayed to users. This approach would split that into "What do we display?" and "How do we display it?"
Idea 2 – Break apart separate components into their own class.
There are several somewhat disjoint components in this code. If this code base were Facebook's – this approach would involve pulling apart the code for photos and the newsfeed.
If we are talking about Javascript, chances are you are using it in a browser. That being the case, most of your code is about views. A MVC pattern won't help you that much because most of your code will handle views.
Remember Javascript is not class based but prototype based. It is also functional. Functional programming excels in manipulating data. Try using the functional aspects of Javascript when doing so.
I suggest you try to split your project into a common framework for retrieving, manipulating and pushing data for all your views; and then splitting your view code into components.
If we are talking about 10k lines, you had to develop some sort of backbone to handle common tasks. If you don't use jQuery, after reorganizing your code, compare your implementation to jQuery's solutions and if you see an improvement, you can start refactoring inside your code.
If you have a chance take a look at Ext JS source code: http://www.sencha.com/products/extjs/download/ext-js-4.0.2a/213
To answer your question: Yes.
I'm not sure what you mean by 'refactor, but not rewrite'. Refactoring code shouldn't change external behaviour, but refactoring will certainly involve some sort of moving code around and whatnot.
Generally, separating the markup from the business logic is a good idea: it's following the model-view-controller pattern, effectively making your markup code 'view' code, and your business logic 'controller' code.
Breaking your code apart into separate components is likewise a good idea. Breaking your code into individual classes supports the idea of having classes with high cohesion and low coupling, and generally moves you towards more SOLID object-oriented design.
If you're asking which one will be more beneficial, that's something that can't be evaluated by the SO community, that's something you have to decide.
Oversimplified, you need to first figure out, in technical terms, what your desired architecture definition is. What is your main file (high-level) responsible for, what your low-scale modules are, and how they will be communicating (directly or vicariously). Should you abstract away the external frameworks at this stage? I am a fan of EDA's (Event-Driven Architectures), Fractal Hierarchies, and Mediation (Mediator Pattern), but many other definitions exist. Choose one that suits the scale of your project and can scale out.
Derive a blueprint and procedure for how you'll get your architecture from A to B. You may want an Abstract Procedure to entail a convention. For instance, "Redundancies: use Decorators" and so on. Do you favor composition over inheritance? However, you should have a Concrete Procedure for how to execute your game plan. E.g: "Replace references to 'X' with Mediator", "Let Save() dispatch a signal on the 'validation' channel", etc.
Make sure you're reflecting your views precisely with your JavaScript compositions. Because it's always a pain to balance unparallel hierarchies -- this ALWAYS leads to entropy. And try to embrace the (noted above) SOLID principles.
I wished to elaborate more, but I hope this is a good start for you.

Categories