TECH |
Engadget Japanese |
ピーター・ティールがMeta取締役を退任へ。Facebook初期からザッカーバーグに助言 |
https://japanese.engadget.com/peter-thiel-is-leaving-metas-board-of-directors-093009767.html
|
facebook |
2022-02-08 09:30:09 |
TECH |
Engadget Japanese |
ソフトバンクG孫社長、Arm売却断念は「むしろ良かったと思うようになる」 |
https://japanese.engadget.com/arm-090401710.html
|
nasdaq |
2022-02-08 09:04:01 |
TECH |
Engadget Japanese |
東大の研究グループが「柔軟なセラミックス」を創り出すことに成功 |
https://japanese.engadget.com/university-tokyo-ceramic-090013682.html
|
東京大学 |
2022-02-08 09:00:13 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
[Python]画像の余白を白埋めして正方形にする方法 |
https://qiita.com/momendoufu/items/e797cefcd59d33d7c77b
|
|
2022-02-08 18:02:55 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
リンクをクリックするとjavascriptで指定の要素にスクロールする方法 |
https://qiita.com/udonkoneko55/items/dccfe565db6fe863ed22
|
|
2022-02-08 18:18:43 |
Linux |
Ubuntuタグが付けられた新着投稿 - Qiita |
脆弱性スキャンツールVulsインストール手順(Docker版) |
https://qiita.com/mj69/items/980aa9fe6341b7aa81ab
|
|
2022-02-08 18:47:00 |
golang |
Goタグが付けられた新着投稿 - Qiita |
RestAPIをCleanArchitectureで実装する際のreq/resの持ち回りについて |
https://qiita.com/470_aaa/items/d5fa354f1c23ebd5a07f
|
※依存性の逆転の原則・上位と下位のレイヤーの両方が抽象に依存すべき・実装が抽象に依存すべき参考感じた違和感上述したコードではcontroller→usecase←repositoryといったように、ApplicationレイヤーusecaseにInterfaceレイヤーcontrollerrepositoryが依存するようになっています。 |
2022-02-08 18:43:01 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
【git】一時退避する方法(メモ) |
https://qiita.com/kai_naka/items/23eb3738195feb64bbc6
|
gitstash |
2022-02-08 18:49:41 |
技術ブログ |
Mercari Engineering Blog |
メルカリShops の技術スタック、その後 |
https://engineering.mercari.com/blog/entry/20220207-mercari-shops-tech-stack-next/
|
hellip |
2022-02-08 10:00:40 |
技術ブログ |
Mercari Engineering Blog |
検索の応答性能を維持するための Benchmarking Automation |
https://engineering.mercari.com/blog/entry/20220207-8ff8aad53e/
|
hellip |
2022-02-08 09:00:50 |
技術ブログ |
Developers.IO |
【アップデート】Amazon CloudFront を経由しないアクセスのブロックが簡単になりました |
https://dev.classmethod.jp/articles/amazon-cloudfront-managed-prefix-list/
|
amazon |
2022-02-08 09:08:50 |
海外TECH |
MakeUseOf |
How to Manually Update Ableton Live to 11.1 |
https://www.makeuseof.com/update-ableton-live-11-1-how-to/
|
windows |
2022-02-08 09:54:49 |
海外TECH |
MakeUseOf |
5 Dad Sites for Fathers to Find Parenting Advice and Practical Tips |
https://www.makeuseof.com/dad-sites-for-fathers-find-parenting-advice-practical-tips/
|
Dad Sites for Fathers to Find Parenting Advice and Practical TipsFrom expert guides to asking other dads for advice these sites have excellent advice for fathers to raise great children they will be proud of |
2022-02-08 09:30:12 |
海外TECH |
DEV Community |
easy user UI login validation |
https://dev.to/alguercode/easy-user-ui-login-validation-2m02
|
easy user UI login validationI made modern user login validation powerd by volder npm package volder project link to github volder is powerful Object schema validation it lets you describe your data using a simple and readable schema and transform a value to match the requirements it has custom error messages custom types and nested schemas |
2022-02-08 09:53:28 |
海外TECH |
DEV Community |
Almost Netflix: An iOS Netflix Clone built with Appwrite |
https://dev.to/appwrite/almost-netflix-an-ios-netflix-clone-built-with-appwrite-5b7
|
Almost Netflix An iOS Netflix Clone built with AppwriteWelcome to the fourth post in our Almost Netflix series We ll be building upon the project setup and build another frontend for our Netflix Clone In this post we will take a closer look at building the clone using iOS In the next post of this series we ll be building frontend for Android This one s all about iOS so let s get started It would be impossible to write every piece of code in this article you will read about all essential concepts components and communication with Appwrite Still if you want to check out every corner of our Almost Netflix for iOS you can check out the GitHub Source Code that contains the whole app What is Appwrite Appwrite is an open source backend as a service that abstracts all the complexity involved in building a modern application by providing you with a set of REST APIs for your core backend needs Appwrite handles user authentication and authorization databases file storage cloud functions webhooks and much more If anything is missing you can extend Appwrite using your favorite backend language RequirementsIn order to continue with this tutorial you will need the following Access to an Appwrite project or permission to create one If you don t already have an Appwrite instance you can install it following our official installation guide Setup Appwrite project following our Almost Netflix server setup guideAccess to XCode or newer Find more about Xcode here Know the basics of iOS development and Swift UI ️Create iOS projectWe will start by creating a new project Open Xcode and select Start New Project On the next screen select iOS gt App then click Next On the next screen give your project a name enter an organization id and for the interface select SwiftUI with language set to Swift then click next On the next screen select the folder where you want to save your new project and click create This will create a new project and open it in Xcode You should now see the following screen ️DependenciesWe will start by adding dependencies For this project we need two packages First the Appwrite SDK and then Kingfisher image package for displaying images from URL In order to add a package go to File gt Add PackagesIn the dialog box that appears tap the top right search icon and type the following GitHub URL for the SDK and hit Enter You should see the sdk for apple package listed Now select the sdk for apple package and on the right side select dependency rule as Up to major version and use version for the latest SDK Now click on the Add Package button Xcode will download the Appwrite Apple SDK along with its dependencies and will add it to your project Make sure the proper target is selected in the Add to target in the dialog as shown above then click Add Package button The package should successfully be added to your project Now following the same process this time search for the Kingfisher package using the GitHub URL as the following Now that we have all our dependencies we will create an AppwriteService class and initialize the Appwrite client database and authentication services Let s start First add a new Swift file and name it AppwriteService swift containing the following class AppwriteService let client Client let database Database let account Account let storage Storage let avatars Avatars static let shared AppwriteService init client Client setEndpoint https YOUR ENDPOINT setProject PROJECT ID setSelfSigned Do not use in production database Database client account Account client storage Storage client avatars Avatars client Using the above code we are initializing our client and database account storage and avatars services Replace YOUR ENDPOINT with your own endpoint and PROJECT ID with your own project ID Now that we have setup our Appwrite client and services we will start implementing authentication in our application AuthenticationWe will start by creating basic views that are required to implement the authentication flow Let s start with login view First create a new SwiftUI View file and name it LoginView swift The full view definition can be found here for now we will focus on the button actions where they defer to a view model we will create later State private var email State private var password EnvironmentObject var authVM AuthVM var body some View VStack Button Login authVM login email email password password Create a similar file named SignupView swift and update with the full view from here This view is largely the same but calls a different method in our AuthVM when the Sign Up button is clicked We now need a view that we can use to switch between login and sign up Create a new file called TitleView swift Here we will focus on the navigation aspect import Foundationimport SwiftUIstruct TitleView View State private var selection String nil var body some View NavigationView VStack NavigationLink destination LoginView tag Sign In selection selection NavigationLink destination SignupView tag Sign Up selection selection Button Sign In self selection Sign In Button Sign Up self selection Sign Up Here we use navigation links inside a navigation view to navigate to sign in or sign up When a user taps one of the buttons the selection state variable is set This way if we were to add more buttons we only need to add new tags not a new state variable for each button We now have a nice title view that navigates to either login or sign up that looks like this Now we need a view to navigate to on successful sign in or sign up Create another file named HomeView swift and update with the following code for now to simply create a dummy home page to make sure the auth flow is complete and correct import SwiftUIstruct HomeView View var body some View NavigationView ZStack Color black ignoresSafeArea We also need a view that will display either a splash UI login UI or the home page based on authentication state Let s create a file named MainView swift and update with the following code import SwiftUIstruct MainView View EnvironmentObject var authVM AuthVM var body some View Group if authVM checkedForUser SplashView else if authVM user nil HomeView environmentObject MoviesVM userId authVM user id else TitleView Now that we have all the views necessary for authentication flow we will create a view model that will handle the authentication logic Create a new swift file and name it AuthVM swift Inside the file create the following class class AuthVM ObservableObject Published var checkedForUser false Published var error String Published var user User We also have defined three variables that will help us track and display the authentication state error and user s details Now let s add a function that will help us create an account Add the following to the AuthVM class func create name String email String password String error AppwriteService shared account create userId unique email email password password name name result in switch result case failure let err DispatchQueue main async print err message self error err message case success self login email email password password Above we have a create method that accepts name email and password and creates a new account using Appwrite s account service Upon successful creation of an account we are also calling login method to create session for the user Let us now add the following login function to our AuthVM public func login email String password String error AppwriteService shared account createSession email email password password result in switch result case failure let err DispatchQueue main async self error err message case success self getAccount The login function accepts an email and password and creates a session using Appwrite s account service Once a session is created we call the getAccount function to get the details of the current user Next let us add the getAccount method that will get the user s account and help us check whether the user is logged in private func getAccount error AppwriteService shared account get result in DispatchQueue main async self checkedForUser true switch result case failure let err self error err message self user nil case success let user self user user To get the user account we are simply calling the get function of the Appwrite s account service Upon success we are setting the user property with the received user details Finally let us add an initializer method to the AuthVM class that will call getAccount so that user s authentication state is checked on application start up init getAccount That s it for authentication Our application will now show a splash screen until we have checked if the user is logged in if they are they will be shown the home screen otherwise the login screen Movies PageLet us head back to the HomeView swift file and start creating our movie carousel views We need to create a horizontal scroll view within a vertical scroll view The vertical scroller will iterate movie categories and the horizontal scrollers will iterate the movies within each category We will first add the vertical scroll to our HomeView as follows ScrollView vertical showsIndicators false if moviesVM featured nil MovieItemFeaturedView movie moviesVM featured isInWatchlist moviesVM watchList contains moviesVM featured id onTapMyList self onTapMyList moviesVM featured id else if moviesVM movies movies isEmpty let movie moviesVM movies movies first MovieItemFeaturedView movie movie isInWatchlist moviesVM watchList contains movie id onTapMyList self onTapMyList movie id VStack alignment leading spacing ForEach appwriteCategories category in MovieCollection title category title movies moviesVM movies category id frame height padding horizontal Let s break that down Inside our scroll view we first check if we have a featured movie If we do this is shown at the top of the page using a MovieItemFeaturedView that we will add later Below the featured movie we have a vertical stack that iterates some pre defined categories and displays a MovieCollectionView for each Now we can create our subviews First create a new file called MovieItemFeaturedView swift and add the following import SwiftUIimport Kingfisherstruct MovieItemFeaturedView View State private var isShowingDetailView false let movie Movie let isInWatchlist Bool let onTapMyList gt Void var body some View ZStack KFImage url URL string movie imageUrl resizable scaledToFill clipped VStack HStack Button onTapMyList label VStack Image systemName self isInWatchlist checkmark plus Text My List NavigationLink destination MovieDetailsView movie movie isActive isShowingDetailView EmptyView Button self isShowingDetailView true label VStack Text Info Our featured movie is now set up so let us move on to the MovieCollectionView Create a new filed called MovieCollectionView swift and update with the following code ScrollView horizontal showsIndicators false HStack ForEach movies movie in MovieItemThumbnailView movie movie frame width itemWidth height itemHeight frame height frameHeight Here we have a scroll view with a horizontal stack inside which iterates each movie within the given collection and displays a MovieItemThumbnailView for each Now we can create a new file MovieItemThumbnailView swift and add the following NavigationLink destination MovieDetailsView movie movie KFImage url URL string movie imageUrl resizable scaledToFit cornerRadius Here our image is nested inside a navigation link so when the image is clicked our app will navigate to the movie detail view That s it for our movie feed We now have a nested scroll view displaying collections of movies by category Now we need to create a detail view for individual movies ️Detail PageNow we can define our movie detail view Create a new file called MovieDetailsView swift Inside the details view we have a button that toggles adding the current movie to a users watchlist Button self addToMyList label VStack Image systemName moviesVM watchList contains movie id checkmark plus Text My List padding func addToMyList gt Void moviesVM addToMyList movie id Now we need to add the MovieGridView which shows similar movies to the one displayed on the detail page Let s add that now as a new file called MovieGridView swift LazyVGrid columns GridItem adaptive minimum alignment leading spacing ForEach movies movie in MovieItemThumbnailView movie movie Our movie detail view will now look like the following ️Movies ViewModelWe need to add the View Model we are using to fetch movies and publish them to the UI This class contains most of the logic for managing the movie feed as well as the currently logged in user s watchlist Add a new file MoviesVM swift with the following class MoviesVM ObservableObject Published var featured Movie Published var movies String Movie Published var watchList String let userId String init userId String self userId userId getMovies getFeatured public func getMyWatchlist AppwriteService shared database listDocuments collectionId movies queries Query equal id value watchList result in DispatchQueue main async switch result case failure let err print err message case success let docs self movies watchlist docs convertTo fromJson Movie from func addToMyList movieId String if self watchList contains movieId removeFromMyList movieId else AppwriteService shared database createDocument collectionId watchlists documentId unique data userId userId movieId movieId createdAt Int NSDate now timeIntervalSince read user userId write user userId result in DispatchQueue main async switch result case failure let err print err message case success self watchList append movieId self getMyWatchlist print successfully added to watchlist func removeFromMyList movieId String AppwriteService shared database listDocuments collectionId watchlists queries Query equal userId value userId Query equal movieId value movieId limit result in switch result case failure let err print err message case success let docList AppwriteService shared database deleteDocument collectionId watchlists documentId docList documents first id result in DispatchQueue main async switch result case failure let err print err message case success let index self watchList firstIndex of movieId if index nil self watchList remove at index self getMyWatchlist print removed from watchlist func isInWatchlist movieIds String AppwriteService shared database listDocuments collectionId watchlists queries Query equal userId value userId Query equal movieId value movieIds result in DispatchQueue main async switch result case failure let err print err message case success let docList let docs docList convertTo fromJson Watchlist from for doc in docs self watchList append doc movieId if docs count gt self getMyWatchlist private func getFeatured AppwriteService shared database listDocuments collectionId movies limit orderAttributes trendingIndex orderTypes DESC result in DispatchQueue main async switch result case failure let err print err message case success let docs self featured docs convertTo fromJson Movie from first if self featured nil self isInWatchlist self featured id private func getMovies appwriteCategories forEach category in AppwriteService shared database listDocuments collectionId movies queries category queries orderAttributes category orderAttributes orderTypes category orderTypes result in DispatchQueue main async switch result case failure let err print err message case success let docs self movies category id docs convertTo fromJson Movie from self isInWatchlist docs documents map id Watchlist PageBonus points We have also implemented a Watchlist feature To add this we need to another new view WatchlistView swift ScrollView vertical showsIndicators false if moviesVM movies watchlist isEmpty MovieGridView movies moviesVM movies watchlist else Text You have no items in your watchlist foregroundColor Color white This view will get all the movies in the users watchlist and display them in our previously created MovieGridView ConclusionTa da We have almost cloned Netflix Swiftly and easily with Appwrite as our backend To become part of the Appwrite community you can join our Discord server We look forward to seeing what you build and who you are when you join our discord With each Appwrite release amazing new features are being added and as they are we will return to our Netflix clone to keep it growing Learn moreGetting Started with AppleSwiftUI PlaygroundAppwrite GithubAppwrite Documentation |
2022-02-08 09:52:44 |
海外TECH |
DEV Community |
AdminLTE v3.2.0 Release |
https://dev.to/sm0ke/adminlte-v320-release-4ib4
|
AdminLTE v ReleaseHello Coders This article presents AdminLTE an iconic dashboard template with k Github stars and used by more than k developers according to GH stats The latest release v comes with a few nice evolutions and fixes The product can be downloaded from Github under the MIT License and used for commercial products and eLearning activities Thanks for reading Content provided by Admin DashboardsAdminLTE v release pageAdminLTE official documentationFor newcomers AdminLTE is a fully responsive administration template Based on Bootstrap framework and also the JS jQuery plugin Highly customizable and easy to use Fits many screen resolutions from small mobile devices to large desktops The product can be compiled and started with ease in a local environment using a decent version of NodeJS and above GIT and a modern code editor like VsCode or Atom Compile AdminLTE from SourcesOnce the sources are downloaded from the official repository the sources can be compiled via Yarn or NPM AdminLTE Clone download sources git clone cd AdminLTEAdminLTE Install modules and start for development npm i install modules via NPM OR yarn install modules via Yarn npm run dev start in development mode with LIVE reload OR yarn dev start in development mode with LIVE reload At this point we should be able to access AdminLTE in the browser and interact with all pages Release SummaryThis section presents a short summary of this update For full information feel free to access the official release page Enhanced Dark ModeSVG Font Awesome Icon supportDocker dev presetReworked Dark Light colorsCustom Scrollbar style Non Plugin Scrollbar The support for Node v is officially dropped AdminLTE UI Elements v AdminLTE Charts page v Thanks for reading For more resources feel free to access More Free Dashboards crafted in Django Flask and ReactMore Admin Dashboards a huge index with products |
2022-02-08 09:15:40 |
海外TECH |
DEV Community |
Django vs Flask, what to choose! |
https://dev.to/jet_ezra/django-vs-flask-what-to-choose-5ceo
|
Django vs Flask what to choose Table of contentsIntroductionFlaskBackgroundWho uses flaskDjangoBackgroundWho uses DjangoSimilaritiesDifferencesConclusion Introduction Hello hope you are doing well well this is knocking at the door and we need to start doing things its new way it is coming along with Whereas there are more than frameworks of Python there are only two of these that have continuously become the kings of the web flask and Django at least as far as These two frameworks seem to be the most mature and most loved on the web by many beginners advanced developers and companies They give us a chance to use the world s best language for full stack development Let s break them and we get to know which to learn and use when Can we roll Flask Background Flask was created by Armin Ronacher of Pocoo an international group of Python enthusiasts formed in According to Ronacher the idea was originally an April Fool s joke that was popular enough to make into a serious application The name is a play on the earlier Bottle framework When Ronacher and Georg Brandl created a bulletin board system written in Python the Pocoo projects Werkzeug and Jinja were developed Flask s philosophy according to this article is to let the developer take on the driver s seat and have total full control over the application they are developing This has made the framework become the no choice to most of the developers that love doing things their own way Flask code sample from flask import Flaskapp Flask name app route def hello return Hello World With the above code you have a full application that outputs Hello World in the browser running on http localhost amazing right Who uses flask Well flask being a python light weight framework most of the companies have picked it to play a big role in building micro services As we have seen in the above code snippet with just one file you have a fully working app Therefore over companies may not entirely be depending on flask as the primary backend framework but include it in their stack This list only shows the top NetflixRedditLyftCREDTrivagoZalandoMITPatreonMLSendcloudAs per this writing Flask had k watches k stars and k forks on github these may have changed by the time you are reading this but you can click here for the current standings Django Django ˈdʒæŋɡoʊ JANG goh sometimes stylized as django is a Python based free and open source web framework that follows the model template views MTV architectural pattern It is maintained by the Django Software Foundation DSF an independent organization established in the US as a c non profit Background Django was created in the fall of when the web programmers at the Lawrence Journal World newspaper Adrian Holovaty and Simon Willison began using Python to build applications Jacob Kaplan Moss was hired early in Django s development shortly before Simon Willison s internship ended It was released publicly under a BSD license in July This framework has been around for over years atleast as per this writing The framework was named after guitarist Django Reinhardt Who uses django Well various applications companies or even tools may not be using Django as the framework but it s counterpart framework Django Rest framework which is a derivative of the same The list shows the companies currently using Django in their progressive work The list only shows the top but there are more DisqusInstagramBitbucketMacArthur FoundationMozillaNational GeographicOpen Knowledge FoundationPinterestOpen StackSpotifyAs per this writing Django had k watches k stars and k forks on github these may have changed by the time you are reading this but you can check the Django repo for the current stand Similiraties Well no matter how they seem to be the two frameworks share somethings in common which you can not under look And the matter of the fact if you are ready comfortable with one you will find it extremely easy to move one to the next Like the process is seamless Here are the similarities you will find in both Python frameworks Well without knowledge of python then you won t be able to write the two frameworks The are highly Object oriented and therefore all functions classes and data structures from python itself can be used in both Fullstack frameworks Both are independent fullstack frameworks that is you will not need any other framework alongside them to develop the backend frontend etc They come with inbuilt template engines to handle the front end and use python to handle the backend ORM for models The frameworks use Object Relational Mappers to provide quick interactions with the database Whereas Flask does not ship in with this functionality a special tool to achieve the same has been developed called Flask SQLAlchamey On the other hand the ORM functionality is in built with django and it s one of those features Django beats most of the other frameworks on Request Response behaviour With both frameworks you will not miss finding features such as views which will receive requests perform some logic and map them to the right response This response maybe returning a new page some json or file Routes urls Whereas the design differs the functionality does not These are mappers which tell the frameworks which view to return on which request Sessions and authentication Whereas you may not start the sessions automatically with flask helper functions for starting updating deleting sessions and performing authentication are provided for by the frameworks Some of these features can be achieved with some extra libraries in flask but relying on external libraries in django is upon you Whichever choice you opt for you will find it easy in both to handle the functionalities In built template engines Whereas they may not entirely be the same the frameworks come with the inbuilt way of building templates what users see With these python functionalities such loops conditionals string laterals and many more are presented Flask uses Jinja but with django you can choose to use Jinja but this is not their default Django has defined its own template engine called django templates which works closely similar to Jinja with little upgrades These are not the only similarities the endless will surely be bigger but you scan from the above for more Next let s move on how the two differ Differences There will be a few distinctions between the two frameworks and that s the reason why I had put it that switching from one to another shall really be seamless Let s see how they differ Architecture Django is MVT That is Model View Template Now do not take View for how other frameworks of MVC Model View Controller take it Model will still be Model View will be equivalent to Controller and Template will equivalent to View in MVC Somehow confusing right please read the docs to understand how django handles this feature Django stores and names these files accordingly and most of them are provided by default On the other hand Flask is a modular framework which means one file can even contain the whole app Whereas the architecture is internally maintained as for django the structure is entirely upon you Flexibility Django is meant for developers who want to get tasks complete in time That s why you will find most of the features provided for by default This may look a good thing and will actually do the right work for you but this means you will have less freedom of updating the defaults which will require extra knowledge of the framework to update these features On the other hand Flask is entirely flexible ground up In brief there is no convention of designing a Flask application This also looks good for the start but when the project starts getting complex new members and or even old team may find it hard to update the code Scalability Flask is highly meant to develop modular applications also known as micro services in the same project This implies that different developers can work on different small modules independent of each other but communicating together However django is somehow different Django itself is considered a project and then inside it you set up as many applications as you feel like This let s django handle even the most complex project with ease Also the development convention of django while creating these apps makes it very simple for one to divide out members to work on different modules within the same project without necessarily handling them in a distributed format Also plugging in a new app is very seamless also and does not affect the other applications ran in the same project Security Whereas in django starting from the user and all the forms of authentications such as creating accounts logging in resetting and changing passwords confirming passwords and many more are inbuilt flask loses out on some of these features and you will end up building them from scratch or depending on third party libraries Features like cryptography click jacking CSRF and worked upon by django by default Learning curve If you already know python Flask should take at most a week to write your first application This differs with django most developers have confessed that understanding the file structure of the framework has become an issue however understanding this flow will make django equally easier Therefore django will require you to at least two weeks to feel comfortable working on a good project ORM Whereas flask depends and works well with Flask SQLAlchamy Django s ORM is a killer From the process of creating models tracking and squashing working with more than one database and changing from one database to the other All these make Django ORM a killer feature especially when it comes to handling complex databases with very many tables Conclusion With that said and more as you will read from other developers the question still stands what do you choose Well I am someone who writes both frameworks and my conclusion is thought about When you are handling something that is not complex at all please choose Flask If you are working on a project with some other framework such as Express or Laravel but wanted some independent feature to be done with python please choose flask Otherwise choose django |
2022-02-08 09:12:13 |
海外TECH |
DEV Community |
Arrow Functions - When and When not to use them ? |
https://dev.to/thenerdydev/arrow-functions-when-and-when-not-to-use-them-a7k
|
Arrow Functions When and When not to use them Hey everyone In this article let us understand When and when not should we use arrow functions This article was first published on Check the website for more interesting articles and tutorials on Web Development Arrow FunctionsWith ES JavaScript has evolved a lot because of the customizations that the new standard brings to the language It has immensely improved our development experienced with the introduction of Next Generation JavaScript features One of such features that ES brings to the table is the Arrow Functions The purpose of writing this article is to make the reader aware about the scenarios where he she should not use arrow functions and instead make use of the good old school function syntax or the function expression syntax We need to be a bit careful as well while using arrow functions because they can affect the readability of our code as well When to use Arrow Functions There are some solid reasons why using arrow functions can be a plus Securing the scope The arrow functions remember their context in which they are defined in and they stick to that So even if we introduce a normal callback function and mix that with a couple of arrow functions then that can lead to messing up of the scope Compact Easier to read and write Just a fat arrow and they can be anonymous as well Code Clarity When every function in your code is an arrow function then a normal function is the one that we rely on for defining the scope So we as developers can always look up the next higher order function statement to figure out the this keyword When not to use arrow functions Defining methods on an objectIn JavaScript as we know a method is a function that we set in a property of the object So right at the time of invoking the method the this keyword points to the object that the method belongs to Now let us talk about Object Literals here Let us say we want to define a method inside an object literal At first you might be tempted to use an arrow function for a method definition within the object literal But let us understand with the help of an example why you should not use an arrow function within the object literals const user stocks stock Amazon price in dollars units bought stock Tesla price in dollars units bought stock Meta Platforms price in dollars units bought get total invested gt console log this window return this stocks reduce acc stock gt acc stock price in dollars stock units bought console log this window const invested amount user get total invested console log invested amount user get total invested method as we can see is defined within an arrow function But if you try the above code the invocation to user get total invested would throw a TypeError because in the above case this stocks would resolved to undefined Now the thing to note here is that when we are invoking the get total invested method on the user object the context in which it is called in is the window object which we can easily verify by comparing this keyword with the window object in the get total invested method as you can see within this method the this keyword points to the window object So in essence this stocks resolves to window stocks and this ultimately gives us undefined because we don t have any stocks property on the window object In order to solve this we can simply switch to the function expression syntax or its shorthand for method definition For this case at the invocation point this keyword would refer to the the thing to the left of the dot at the invocation point Here is the code with the above modifications const user stocks stock Amazon price in dollars units bought stock Tesla price in dollars units bought stock Meta Platforms price in dollars units bought get total invested console log this user return this stocks reduce acc stock gt acc stock price in dollars stock units bought const invested amount user get total invested console log invested amount Now in the above code get total invested is a method that is being called on the user object So with the regular function syntax the thing to the left of dot which is the user object here is what this resolves to in the end and therefore the above code would work fine Here is the output for the above code From the output you can also easily decipher that the this keyword indeed points to the user object and hence this user returns true as a result Let us now move forward and take arrow functions with Object Prototypefunction User name age profession this name name this age age this profession profession User prototype sayHello gt console log this window return Hello this name const user new User Alex Developer console log user sayHello Now here also the same thing holds true as discussed above In the above code instead of using the arrow function syntax for defining our sayHello method where the this keyword points to window we should instead use the function expression syntax to solve this So here is the modified code function User name age profession this name name this age age this profession profession User prototype sayHello function console log this window return Hello this name const user new User Alex Developer console log user sayHello So with just this simple change sayHello regular function is changing its context to user object when called as a method user sayHello Arrow Functions cannot be used as constructorsFor constructors use regular functions otherwise JavaScript will throw an error if it encounters an arrow function getting used as a constructor This means that JavaScript implicitly prevents from doing that by throwing an exception Let us go a bit deeper inside and try to understand a bit more on this In simple words the objects or the constructors rely on the this keyword to be able to be able to be modified The this keyword always references the global object which is the window object So if we have something like this const User name age profession gt this name name this age age this profession profession const user new User Alex developer Executing new User Alex developer where User is an arrow function JavaScript throws a TypeError that User cannot be used as a constructor But instead if you do something like this const User function name age profession this name name this age age this profession profession const user new User Alex developer console log user name Now here the new keyword does some magic under the hood and makes the this keyword that is inside the User to initially first refer to the empty object instead of referencing to the global object like it earlier did Right after this new properties like name age and gender get created inside this empty object pointed to by the this keyword and the values will be Alex and developer respectively Finally the object pointed to by the this keyword gets returned Now a thing to note here is that arrow functions do not allow their this object to be modified Their this object is always the one from the scope where they were statically created This is called Static Lexical Scope This is precisely the reason that why we cannot do operations like bind apply or call with arrow functions Simply their this is locked to the value of the this of the scope where they were created Arrow Functions as callback functionsAs we know in client side JavaScript attaching event listeners to the DOM elements is a very common task An event triggers the handler function with this as the target element So for example let us say we have this code const button document querySelector button button addEventListener click gt console log this window this innerHTML Changed Now as discussed just a while back this points to the window object in an arrow function that is defined in the global context So whenever a click event occurs browser tries to execute the handler function with the button as context but arrow functions still stays bound to its pre defined context In above code this innerHTML is same as window innerHTML which does nothing infact In order to solve this we need to make use of the function expression syntax which will allow us to change this depending on the target element const button document querySelector button button addEventListener click function console log this button this innerHTML Changed Now for the above code this keyword will infact point to the button Therefore this innerHTML will correctly modify the button text and reflect the same in the UI So this is it for this article Thanks for reading If you enjoy my articles consider following me on Twitter for more interesting stuff Twitter Don t forget to leave a like if you loved the article Also share it with your friends and colleagues PS If you are looking to learn Web Development I have curated a FREE course for you on my YouTube Channel check the below article Web Developer Full Course HTML CSS JavaScript Node js and MongoDB The Nerdy Dev・Apr ・ min read html css node javascript Looking to learn React js with one Full Project check this out Learn React with one BIG Project NOTES included Demo and Video Link The Nerdy Dev・Jun ・ min read daysofcode javascript react webdev |
2022-02-08 09:01:05 |
海外TECH |
Engadget |
Leak confirms Samsung's Galaxy Tab S8 lineup |
https://www.engadget.com/samsungs-galaxy-tab-s-9-lineup-confirmed-by-leak-093529091.html?src=rss
|
Leak confirms Samsung x s Galaxy Tab S lineupJust ahead of Samsung s Unpacked event set for tomorrow a press release for Samsung s Galaxy Tab S lineup has been revealed by leakmeister Evan Blass The Verge has reported It confirms many key specs from earlier leaks including the existence of an quot Ultra model quot the screen sizes charging capacity and more Samsung will have three models in the lineup including the inch Galaxy Tab S inch S Plus and big inch S Ultra The latter will feature x resolution with a notch to accommodate the front facing camera The other two models will come with x and x screens respectively nbsp Other features include support for fast WiFi E with optional G watt fast charging and a new S Pen Stylus All models offer a megapixel megapixel ultrawide rear camera setup with a megapixel ultra front camera The Ultra model however has a second front facing megapixel wide camera hence the aforementioned notch Samsung may also offer an optional keyboard cover nbsp The Galaxy Tab S lineup will arrive on February th in select markets including the US Europe and Korea according to the press release Pre orders will open in those markets on February th at AM ET nbsp |
2022-02-08 09:35:29 |
医療系 |
医療介護 CBnews |
都立府中療育・北療育医療センター職員がコロナに-福祉保健局が発表、健康安全研究センター職員も |
https://www.cbnews.jp/news/entry/20220208175438
|
健康安全研究センター |
2022-02-08 18:05:00 |
金融 |
金融庁ホームページ |
入札公告等を更新しました。 |
https://www.fsa.go.jp/choutatu/choutatu_j/nyusatu_menu.html
|
公告 |
2022-02-08 11:00:00 |
金融 |
ニッセイ基礎研究所 |
コロナ禍でも成長を持続する少額短期保険業界-大手生損保会社による少額短期保険子会社の設立も相次ぐ- |
https://www.nli-research.co.jp/topics_detail1/id=70186?site=nli
|
」 と し て いる 。 |
2022-02-08 18:28:42 |
ニュース |
@日本経済新聞 電子版 |
鍵山2位・宇野3位・羽生出遅れ8位 フィギュア男子SP
https://t.co/HgFnvyP9th |
https://twitter.com/nikkei/statuses/1490974865217650690
|
鍵山 |
2022-02-08 09:04:43 |
ニュース |
@日本経済新聞 電子版 |
TDL・代替保育・抗原検査キット
https://t.co/jgT1stnIhi |
https://twitter.com/nikkei/statuses/1490974864211320833
|
検査 |
2022-02-08 09:04:43 |
ニュース |
@日本経済新聞 電子版 |
人権リスク、海外取引先を調査 経産省がILO専門家派遣
【日経イブニングスクープ】
https://t.co/RJOSepOfgS |
https://twitter.com/nikkei/statuses/1490974861866717185
|
調査 |
2022-02-08 09:04:42 |
ニュース |
BBC News - Home |
No 10 has no intention of apologising after protesters surround Sir Keir Starmer |
https://www.bbc.co.uk/news/uk-politics-60297998?at_medium=RSS&at_campaign=KARANGA
|
boris |
2022-02-08 09:06:41 |
ニュース |
BBC News - Home |
BP profits surge amid calls for windfall tax |
https://www.bbc.co.uk/news/business-60299886?at_medium=RSS&at_campaign=KARANGA
|
prices |
2022-02-08 09:07:36 |
ニュース |
BBC News - Home |
Britain will not flinch over Ukraine, Boris Johnson tells Russia |
https://www.bbc.co.uk/news/uk-60300323?at_medium=RSS&at_campaign=KARANGA
|
moscow |
2022-02-08 09:20:51 |
ニュース |
BBC News - Home |
Ormeau Road attack: Police 'collusive behaviour' in murders |
https://www.bbc.co.uk/news/uk-northern-ireland-60287855?at_medium=RSS&at_campaign=KARANGA
|
failures |
2022-02-08 09:12:55 |
ニュース |
BBC News - Home |
Long Covid: 'My shame over 18-month work absence' |
https://www.bbc.co.uk/news/uk-wales-60287344?at_medium=RSS&at_campaign=KARANGA
|
griffiths |
2022-02-08 09:27:29 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
JFEホールディングス(5411)、「増配」を発表して、 配当利回り8.9%に! 年間配当は1年で14倍に急増、 2022年3月期は前期比130円増の「1株あたり140円」 - 配当【増配・減配】最新ニュース! |
https://diamond.jp/articles/-/295756
|
|
2022-02-08 18:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【日本株】消去法では「旅行・レジャー」など“アフター コロナ”関連株が狙い目も無理は禁物! 将来の「難易度 が著しく下がる相場」で勝負できる余力を残しておこう - 成り上がり投資術 |
https://diamond.jp/articles/-/295743
|
|
2022-02-08 18:30:00 |
北海道 |
北海道新聞 |
元札響コンマス、大平まゆみさんに札幌市長特別表彰 |
https://www.hokkaido-np.co.jp/article/643363/
|
大平まゆみ |
2022-02-08 18:16:44 |
北海道 |
北海道新聞 |
チェン、振り払った4年前の悪夢 別格の存在、世界最高得点 |
https://www.hokkaido-np.co.jp/article/643365/
|
平昌冬季五輪 |
2022-02-08 18:12:00 |
北海道 |
北海道新聞 |
羽生に「引きずらず良さ出して」 地元仙台、高校の元顧問らが願い |
https://www.hokkaido-np.co.jp/article/643364/
|
男子ショートプログラム |
2022-02-08 18:09:00 |
IT |
週刊アスキー |
『FFXIV』で期間限定イベント「ヴァレンティオンデー」が開催! |
https://weekly.ascii.jp/elem/000/004/082/4082922/
|
ffxiv |
2022-02-08 18:55:00 |
IT |
週刊アスキー |
うれしい報酬がどっさり!PC『ガンダムジオラマフロント』で「バレンタインキャンペーン」を開催! |
https://weekly.ascii.jp/elem/000/004/082/4082923/
|
目標達成 |
2022-02-08 18:50:00 |
IT |
週刊アスキー |
“北海道”グルメをブッフェ形式で! 紅ズワイガニも登場の期間限定ブッフェ、横浜ベイホテル東急で3月1日から |
https://weekly.ascii.jp/elem/000/004/082/4082911/
|
北海道産 |
2022-02-08 18:30:00 |
IT |
週刊アスキー |
象印、店でマイボトルを保管しロッカーで飲み物を受け取れるサービス |
https://weekly.ascii.jp/elem/000/004/082/4082916/
|
実証実験 |
2022-02-08 18:30:00 |
マーケティング |
AdverTimes |
電子版と本紙販売を集約 日経、サブスク事業に統合・再編 |
https://www.advertimes.com/20220208/article376533/
|
情報サービス |
2022-02-08 09:59:36 |
コメント
コメントを投稿