React - Components to create and update db model, inheritance or composition? - javascript

I'm relatively new to React. My use case implies a create page for a database model and an update page. I have a lot of duplicate code in those and coming from regular OOP design I would create a base class for it and let the two component inherit.
However, after reading several forums, I saw that you should mostly prefer composition over inheritance with React. Would that also apply in this use case? It seems odd to model this via composition.

I think composition also applies to your use case. From what I understand you will have almost the same page for update and create, all your model files will be the same in both cases. So you can make a reusable component, some form. And use it in create and update page, just perform the right action for each of them.

Related

Share code with composition Api in Vue (defineProps, defineEmits and defineExpose)

I'm migrating a midlevel app from Vue 2 to Vue 3.
For this task, I'm rewrittig all code to make use of Composition Api. I like Composition Api, however, I don't see a good advantage when simplifying code. With Composition Api, somethings looks more complex or verbose than before. I hope be wrong.
This becomes specially noticiable when refactoring mixings. When using mixins, you just have to use them and that's enought to get all desired functionality, while when using composables, you have to be aware of what is inside the composable to extract/use specific functionality from composable...
My main problem arises when I want to reuse defineProps(), defineEmits() and defineExpose().
In some parte of my app, I got all posible inputs defined in different components, for example:
InputText: Just text
InputNumber: Reusing InputText, limiting to only numbers
InputMoney: Reusing InputNumber, adding some money formatting
InputNumberRange: Reusing two InputNumbers
etc
As you can imagine, all that inputs are almost the same. The needed code for those components are very small, just a InputMixin and a couple of overwrites if needed.
However, when using Composition Api, I don't know how to get it so simple because I don't know how to 'share' the code between these components. How could I reuse defineProps(), defineEmits() and defineExpose() between them?
Is it possible to use some kind of inheritance? (like extends: MyComponent)

Usage of mutable objects inside React Native + Redux app

I'm new to React (and React Native in particular), and I'm trying to come up with the right application design.
I have a separate JavaScript module, unrelated to React; the module contains some objects with methods, some of them mutate objects, some have side effects (like, subscribe/unsubscribe to/from the server events, or add/remove listeners to local object's events), etc.
I'd like to reuse this JavaScript module inside my React Native app, but it seems that it won't play well together. In Redux (and some other state managers as well), state needs to be represented as a plain immutable JS object, and instead of mutating existing objects, we create new objects instead. So I can't use my existing JS objects as a state directly.
I probably could use some wrappers around my existing JS code (mutating, and full of side effects), but it doesn't seem a nice solution: a lot of repetition, and the end result is unlikely to be elegant.
On the other hand, I'm not quite happy reimplementing the whole thing to fit into React's world, to make it idiomatic.
And on the one more other hand, I could just forget about Redux, and use plain state of React's components, but I feel it'll be a mess.
I'd like to get some suggestions from experiensed React + Redux people. What would you recommend?
It's hard to say exactly without seeing what the mystery module does or exposes. But consider converting the module into one or more reducers and then use Redux's combineReducers to target pieces of the overall store that will be contained exclusively in your module.
Then you will need to add reducer methods that always return new objects as required by Redux, but you won't need to modify every function in the existing code.
This article by Dan Abramov helped me understand reducer composition.
See also Handling Actions in the docs for help on how to write good reducer methods that only modify a small piece of the store.

Classroom Examples for decoupling software components

I'm trying to get to grips with highly-decoupled, low-cohesion patterns for designing components.
I'm designing each Feature of a larger system as a Web Component - analogous to the concept of a "Module" in design patterns, e.g Export-PDF functionality, Boards functionality etc.
The issue is that some components are dependent between them - they call methods of each, have access to their public variables etc.
Since each component needs to be testable in isolation, must be highly-decoupled, must have low inter-dependency with other components, what are some classroom examples for decoupling one from one another?
Considering this scenario:
User presses CTRL+P
Keybindings are handled by the Shortcuts Component
Shortcuts Component calls Export-PDF Component .print() method.
Some solutions I've though about:
Use events
Each component dispatches an event which is then caught in the other component, e.g using this.addEventListener(...
Pros:
Allows testing in isolation since there are no direct calls to another component's methods.
Cons:
Will result in many dispatches/listeners which might impact performance.
There is still a lot of coupling and it has the potential of getting unmanageable.
Use direct calls to methods of the other component
Each component simply calls the other components method directly, e.g exportPDF.printPages().
Pros:
It's the most simple.
Cons:
Each component is interdependent to one another.
Component is NOT testable in isolation.
What are some other methods of decoupling components?
For the record, the language of interest is JavaScript.
Although concepts and methods might be applicable across many programming languages, I'm specifically talking about concepts and solutions to the problems using features that JavaScript has.

When should I use KnockoutJS Components vs. Templates?

So trying to get my hands dirty with KnockoutJS 3.2. I've read the docs and I've successfully implemented components within my current project. I don't use an AMD, so I'm just using script elements to hold the views.
My question is: If i'm not using the asynchronous loading features, is there any real practical difference to using components rather than templates?
General description of both
As stated in the other answer, a template is only a piece of HTML which can be bound to a viewmodel, or viewmodel section. And a component is composed of a template, and its corresponding viewmodel. Besides, this viewmodel, apart from observables can include some simple business logic, and functionality to communicate with the server.
Coupling and encapsulation
Another important difference is the coupling. A template it's bound to the main viewmodel, and its bound to the main viewmodel's observables, so it's highly coupled to the viewmodel: a change in the viewmodel will break the template, and viceversa. So, if you're reusing a template in several places, and you change it, you have to correct the corresponding viewmodels.
A component is bound to its own viewmodel. It's only coupled to the main viewmodel if there are parameters provided from it. This means that you can easily change the component template as well as the component viewmodel, and, if there are no parameters, or you don't change them, nothing will be broken.
So using components helps in decoupling and modularizing.
Communication between main viewmodel and component
The last section is a double edged sword: if there is a high interaction between the main viewmodel and the template or component, it's much easier to use a template, because all the logic and properties are held in the main viewmodel and the interactions are easily implemented. If you used a component you'd need to provide complex parameters, or even make something to allow the component to expose functionality to the main viewmodel.
Polymorphism
It's not strange to have some parts of an application that require different behaviors and visualization to solve the same kind of task. For example, let's imagine you have to implement a payment system in your application: if you accept for example paypal and credit card payment you have two different visualization and functionalities. If you used templates, you'd need to have the particular implementation of each payment system in the main viewmodel. If you used components, they'd share a common interface (parameters) but each of them would have its own implementation. If tomorrow you had to include a new payment system, it would be easy to implement a new component with the common interface.
NOTE: pay attention to the last paragraph
Binding
In the case of a template the binding it's not done at the template level, but inside it. I.e. each element inside the template must be bound to observables of the main viewmodel. In the case of a component the binding is much simpler: at most, it requires the component name and the parameters, if they exist.
Component registration and custom tags
If you register the component you can use custom tags. This makes the views more easyly readable and understandable: instead of specifying the component name in a binding, you use a tag with the component name, and parameters are passed as attributes.
Dynamic loading
If you use templates you have to dynamically load them by yourself, and, as this is an asynchronous task, you'll have to take care of using the template only when it's already available. That's way in most occasions you'll use inline templates. This is not good if they must be reused in several places.
If you have used some AMD implementation, like require.js, and you understand the benefits of this technology, you'll be happy to know that you can easily use AMD to load component templates and viewmodels. One of the advantages is that you don't have to worry about the template or component being available when you need to use them.
Testability
No matter if you do manual or automated tests, it's much easier to test a bunch of independent components, one by one, that to test a complex viewmodel with or without templates.
My choice
So far, I've exposed facts about templates, and components, and I've tried not to show my personal preferences. However, in this last section, I must say that in most situations I prefer to use components for their advantages:
modularity
low coupling
easy reuse
testability
binding syntax
(optional) dynamic loading
However, templates are also a better fit on some occasions
The last paragraph have to do with big applications. If you're dealing with small applications or simply enhancements of interfaces rendered by another technology (like ASP.NET MVC), you'll probably get none of the advantages of using components. So, you don't need them.
There are other cases when it's not worth using components. For example, if you have to show a list (JavaScript array) of items which have different properties which must be shown in a different way, it's easier to use templates. Note that the choice in this case is because each of the instances doesn't have a complex viewmodel with a lot of functionality, but a simple bunch of properties. In this particular case it's not only not worth, but it can also be counterproductive to use components.
You can understand this last example as polymorphism. But, in this case it's nearly "visual" polymorphism. I.e. each kind of item must be shown in a different way, but there is no need to implement any special logic in each of the components.
However, even in this case, if the templates are complex enough, or must be used in many different places, it's also much better to use a simple component that includes the template as well as a parameter that receives the whole item. So, even in this case, it's not a bad idea to use components.
If you'd read this far, thank you, and I hope you have some criteria to help you choosing the best option.
They aren't completely different. Components are made up of templates (html) and data/logic (view model i.e. JavaScript). When you have a modular view you want to attach a view model to you can utilize components. Here's a link discussing components a bit more: http://www.knockmeout.net/2014/06/knockout-3-2-preview-components.html

ExtJS MVC conventions, naming and behavior

Lately (2.x / 3.x) I just used xtype & factory methods to receive a instance of a class which was as simply as fast. Now I have started 4.x and my first App with MVC. As described in the tutorial the MVC pattern requires me to extend a class for each view I wan't to use, even if I use it just one time. But the best practice written by Sencha itself says:
just extend for re-useability or adding of functionality
In my case I need to register a whole bunch of classes even if they could be created from one base class except of some params like title, width,...
Another point is that the Controller overwrites any StoreId by convention and also requires a strict typing, means the class-name must end with an s. But as far as I know I cannot spare neither the model nor the store within the the controller store/model-array so is there any other point for this convention cause it seems not to spare typing.
Next point is that after merging from 3.X to 4.X the application initial load time has extended which seems to be caused due to either the many new classes that need to get defined or due to the fact that all controllers get instantiated at startup due to the default behavior of the MVC pattern. Is there any way to not auto instantiate a controller and just doing it lazy, for example when I request it on the application controller?
Yes I know, that are a bunch of questions but I guess they all around the same topic.
EDIT
After some sourcecode-digging I am no longer sure about the
requirement of the s when naming a store. I thought I stumbled over
this while going through the MVC tutorial. Can anyone verify this?
EDIT 2
My conclusions
Lacy rendering is quite simple. First of all the Controller should not be mentioned in the ApplicationController controller array. To create a instance of such a controller use the ApplicationController.getController(pureClassName)
[Note that each controller contains a reference to the ApplicationController called application] Now you need to be aware of the fact that the init(application) method and the onLaunch(application) method get no longer invoked by the ApplicationController, you need to do this yourself. When calling getController() the ApplicationController first lookup if there is already a instance of this controller in the internal reference cache if not it creates a instance and inject the controllername as Id. So controllers are a sort of singleton which is perfectly fine.
The controller itself creates all the getter for the registered stores, models and views and, that's a guess, it instantiate them (at least the stores)
About naming restrictions for stores, there no restrictions about ending with an s.
These are very valid points.
First, it has to be mentioned that you don't have to use MVC with ExtJS 4. You can still use ExtJS 3 style in your code.
I assume that if you understand the advantages of MVC and decide to adapt it, then yes - you will have to extend classes and there is some overhead, but admittedly you will end up with a cleaner, more reusable code. It has to be said that while you need to extend top-level views, the items within them can still be coded old style. In addition to this, within the init() of the controller you can modify certain view configs (which allows less of class extension, but more controller code).
I have to admit that if you have experience with ExtJS 3 and you're migrating to MVC style of an app, you will eventually see that the benefits outweigh the work involved.
Personally it's the first time I've been made aware of this 's' business with stores. So I can't comment much on this.
Lastly, a properly-written ExtJs 4 app, one that makes use of dynamic loading should load faster than an ExtJS 3 app. You can also compile an Ext version that only includes code used in your app. And yes, you can instantiate controllers (and their views and stores) when you need them, which works like a charm:
loadPage: function(aControllerName)
{
// save recent page in a cookie
Ext.util.Cookies.set('RecentPage', aControllerName);
// Dynamically load the controller
var iController = this.getController(aControllerName);
// Manually initialise it
iController.init();
// Load the page (by getting the first view of the controller).
var iPage = this.getView(iController.views[0]).create();
// Add the page to the content panel.
var iContentPanel = this.getContentPanel();
iContentPanel.removeAll(true);
iContentPanel.add(iPage);
iContentPanel.doLayout();
}
1.Izhaki answered your question well about the lazy controller initialization.
2.I am not really following you on the gripe about Store names. There are no restrictions on store names. They are merely suggestions of naming conventions.
3.The Ext.define method is great to define your classes - similar to Java or other OO languages. This is NOT required however and you can simply use Ext.create method to create an instance of a framework component and pass it custom config object.
You can also use Ext.define to create you base class and then call Ext.create('MyBaseClass',{title:'mynew tile'}); to get a slightly modified version of your base class.
I encourage you to read through the Sencha guides on MVC, and Class system and also review their examples to get better understanding.

Categories

Resources