One place for hosting & domains

      Design

      Observer Design Pattern in JavaScript



      Part of the Series:
      JavaScript Design Patterns

      Every developer strives to write maintainable, readable, and reusable code. Code structuring becomes more important as applications become larger. Design patterns prove crucial to solving this challenge – providing an organization structure for common issues in a particular circumstance.

      The design pattern below is only one of many useful patterns that can help you level up as a JavaScript developer. For the full set, see JavaScript Design Patterns.

      There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the $scope object updates, an event can be triggered to notify another component. The observer pattern incorporates just that – if an object is modified it broadcasts to dependent objects that a change has occurred.

      Another prime example is the model-view-controller (MVC) architecture; The view updates when the model changes. One benefit is decoupling the view from the model to reduce dependencies.

      Observer Design PatternObserver Design Pattern on Wikipedia

      As shown in the UML diagram, the necessary objects are the subject, observer, and concrete objects. The subject contains references to the concrete observers to notify for any changes. The Observer object is an abstract class that allows for the concrete observers to implements the notify method.

      Let’s take a look at an AngularJS example that encompasses the observer pattern through event management.

      // Controller 1
      $scope.$on('nameChanged', function(event, args) {
          $scope.name = args.name;
      });
      
      ...
      
      // Controller 2
      $scope.userNameChanged = function(name) {
          $scope.$emit('nameChanged', {name: name});
      };
      

      With the observer pattern, it is important to distinguish the independent object or the subject.

      It is important to note that although the observer pattern does offer many advantages, one of the disadvantages is a significant drop in performance as the number of observers increased. One of the most notorious observers is watchers. In AngularJS, we can watch variables, functions, and objects. The $$digest cycle runs and notifies each of the watchers with the new values whenever a scope object is modified.

      We can create our own Subjects and Observers in JavaScript. Let’s see how this is implemented:

      var Subject = function() {
          this.observers = [];
      
          return {
          subscribeObserver: function(observer) {
              this.observers.push(observer);
          },
          unsubscribeObserver: function(observer) {
              var index = this.observers.indexOf(observer);
              if(index > -1) {
              this.observers.splice(index, 1);
              }
          },
          notifyObserver: function(observer) {
              var index = this.observers.indexOf(observer);
              if(index > -1) {
              this.observers[index].notify(index);
              }
          },
          notifyAllObservers: function() {
              for(var i = 0; i < this.observers.length; i++){
              this.observers[i].notify(i);
              };
          }
          };
      };
      
      var Observer = function() {
          return {
          notify: function(index) {
              console.log("Observer " + index + " is notified!");
          }
          }
      }
      
      var subject = new Subject();
      
      var observer1 = new Observer();
      var observer2 = new Observer();
      var observer3 = new Observer();
      var observer4 = new Observer();
      
      subject.subscribeObserver(observer1);
      subject.subscribeObserver(observer2);
      subject.subscribeObserver(observer3);
      subject.subscribeObserver(observer4);
      
      subject.notifyObserver(observer2); // Observer 2 is notified!
      
      subject.notifyAllObservers();
      // Observer 1 is notified!
      // Observer 2 is notified!
      // Observer 3 is notified!
      // Observer 4 is notified!
      

      Publish/Subscribe

      The Publish/Subscribe pattern, however, uses a topic/event channel that sits between the objects wishing to receive notifications (subscribers) and the object firing the event (the publisher). This event system allows code to define application-specific events that can pass custom arguments containing values needed by the subscriber. The idea here is to avoid dependencies between the subscriber and publisher.

      This differs from the Observer pattern since any subscriber implementing an appropriate event handler to register for and receive topic notifications broadcast by the publisher.

      Many developers choose to aggregate the publish/subscribe design pattern with the observer though there is a distinction. Subscribers in the publish/subscribe pattern are notified through some messaging medium, but observers are notified by implementing a handler similar to the subject.

      In AngularJS, a subscriber ‘subscribes’ to an event using $on(‘event’, callback), and a publisher ‘publishes’ an event using $emit(‘event’, args) or $broadcast(‘event’, args).



      Source link

      Singleton Design Pattern in JavaScript



      Part of the Series:
      JavaScript Design Patterns

      Every developer strives to write maintainable, readable, and reusable code. Code structuring becomes more important as applications become larger. Design patterns prove crucial to solving this challenge – providing an organization structure for common issues in a particular circumstance.

      The design pattern below is only one of many useful patterns that can help you level up as a JavaScript developer. For the full set, see JavaScript Design Patterns.

      A Singleton only allows for a single instantiation, but many instances of the same object. The Singleton restricts clients from creating multiple objects, after the first object created, it will return instances of itself.

      Finding use cases for Singletons is difficult for most who have not yet used it prior. One example is using an office printer. If there are ten people in an office, and they all use one printer, ten computers share one printer (instance). By sharing one printer, they share the same resources.

      var printer = (function () {
      
          var printerInstance;
      
          function create () {
      
          function print() {
              // underlying printer mechanics
          }
      
          function turnOn() {
              // warm up
              // check for paper
          }
      
          return {
              // public + private states and behaviors
              print: print,
              turnOn: turnOn
          };
          }
      
          return {
          getInstance: function() {
              if(!printerInstance) {
              printerInstance = create();
              }
              return printerInstance;
          }
          };
      
          function Singleton () {
          if(!printerInstance) {
              printerInstance = intialize();
          }
          };
      
      })();
      

      The create method is private because we do not want the client to access this, however, notice that the getInstance method is public. Each officer worker can generate a printer instance by interacting with the getInstance method, like so:

      var officePrinter = printer.getInstance();
      

      In AngularJS, Singletons are prevalent, the most notable being services, factories, and providers. Since they maintain state and provides resource accessing, creating two instances defeats the point of a shared service/factory/provider.

      Race conditions occur in multi-threaded applications when more than one thread tries to access the same resource. Singletons are susceptible to race conditions, such that if no instance were initialized first, two threads could then create two objects instead of returning and instance. This defeats the purpose of a singleton. Therefore, developers must be privy to synchronization when implementing singletons in multithreaded applications.

      Conclusion

      Design patterns are frequently used in larger applications, though to understand where one might be advantageous over another, comes with practice.

      Before building any application, you should thoroughly think about each actor and how they interact with one another. After reviewing the Module, Prototype, Observer, and Singleton design patterns, you should be able to identify these patterns and use them in the wild.



      Source link

      How to Design a Website Without Knowing How to Code


      As a small business owner, the importance of owning a website cannot be overstated. When you’re just starting out, however, you may not have the funds to hire a web designer. So the task falls to you or your team instead.

      The good news is that you can build a website yourself without getting bogged down with any technical details. Using WP Website Builder, DreamHost’s suite of premium tools and plugins, you can quickly set up a professional, easily-customizable website — no coding knowledge required!

      In this post, we’ll walk you through setting up a basic hosting plan with WordPress and WP Website Builder pre-installed, which you can use to create a responsive website from scratch. Let’s get to work!

      We’ve Got the Ultimate Web Design Tool

      When you partner with DreamHost, you get access to WP Website Builder and more than 200+ industry-specific starter sites for free!

      An Introduction to WP Website Builder

      The landing page for WP Website Builder.

      It can be challenging to design a unique, fully-functional website from scratch. Going the traditional route requires you to learn, at the very least, web design languages like HTML and CSS. You also need to consider responsiveness across different devices, cross-browser compatibility, and accessibility for different types of users.

      Enter WP Website Builder!

      Built by our friends at BoldGrid, WP Website Builder is a drag-and-drop tool for creating websites with minimal effort. You’ll get access to a huge selection of professional website templates, making it simple to create a unique-looking site and publish your content quickly. And while you don’t need any coding skills to use WP Website Builder, you’ll be able to scale up your site’s functionality over time because it’s built with WordPress, the world’s most popular content management system (CMS).

      Best of all, as a DreamHost user, you get access to WP Website Builder for free! All you need is one of our Shared or DreamPress plans.

      How to Design a Website Without Knowing How to Code (In 6 Steps)

      So how can you get started with your new site? The following six steps will take you from purchasing a hosting plan all the way through building a website.

      Step 1: Create a DreamHost account

      Shared hosting plans come cheap and are perfect for getting your small business off the ground. You get a user-friendly interface with a no-stress one-click installer and the flexibility to build any kind of website: whether that’s an e-commerce store, a business website, or a blog.

      For new website owners, we’d suggest starting out with either a Shared Starter or Shared Unlimited plan. On the checkout page, tick the checkboxes shown below, either under the Additional Options section or in the right-hand menu, to pre-install WordPress and include WP Website Builder.

      The checkout page for the DreamHost Shared Unlimited plan.

      If you already have an account, you can access your DreamHost control panel to add WP Website Builder to an existing WordPress installation instead.

      Step 2: Access Your Website and Choose a Theme

      At this point, you’ll want to log in to your new WordPress website. You’ll be presented with the BoldGrid Inspirations wizard, which will walk you through much of the setup process. Click on the Let’s Get Started button to begin.

      The WP Website Builder BoldGrid Inspirations wizard.

      Next, you’ll want to choose a theme for your website. This will provide a starting point and help to determine your content’s appearance and layout.

      The Inspiration wizard theme selection screen.

      Hover over any theme to see it more closely, and click on the Select button to apply it to your site. We’ll go ahead and select the Cobalt theme. Keep in mind that you can always change your theme later, and you’ll also be able to customize many of its elements and styles.

      Step 3: Choose Your Content Structure

      Once you’ve selected a theme, the next thing to do is choose a content structure. Click on the Change Content button to begin.

      The Inspiration wizard Content screen.

      You’re given three Pageset options: Base, Five Page, and Kitchen Sink. You can also choose whether or not your website will have a blog.

      Adding a blog to your site.

      The Content screen also lets you see how responsive your website will be across different screen sizes. That way, you’ll know what it will look like for both desktop and mobile users.

      Step 4: Enter Essential Site Information

      This next screen lets you fill in information that will be used to populate key aspects of your website, such as your contact information and social media account details. You can also leave this screen as-is and edit these details later.

      The Inspiration wizard Essentials screen.

      Once you’re done here, select the Finish and Install button to complete the installation.

      Step 5: Design Your Pages and Posts With the Drag-and-Drop Builder

      After the installation is complete, you’ll be presented with your WordPress dashboard. The next step is to begin customizing your website by adding new pages and posts (if your site includes a blog).

      The WordPress dashboard.

      We’ll start by adding a new page called Documentation and include some content on the page using blocks.

      The Add New Page screen.

      The next screen is divided into two sections. The right-hand side of the page gives you a selection of blocks, and the left shows you a preview of what your page will look like once it’s live.

      Hover over an appropriate block and click the + Add to Page button.

      The Add New Page screen.

      Here’s what our page looks like once a few blocks have been added.

      A new page with multiple content blocks.

      Once you’re satisfied with a block, select the checkmark icon to accept it. 

      Step 6: Customize Your Blocks and Publish Your Content

      After adding a block, you’ll be taken back to the main editing screen. This is where you can edit the blocks you added or include entirely new content.

      The Add New Page screen.

      When you’re done editing, preview your page to make sure you’re satisfied with the look, and then select the Publish button to make it live.

      Publishing a new page.

      If you chose to include a blog on your website earlier, you can create posts just as easily now. Click on the Add New link that appears when you hover over the Post menu.

      Creating a new post.

      You can then create your post exactly the same way your page was designed. Clicking the + button will open a menu with different types of block options. Once you’ve created your post, preview and publish it, or save it as a draft to continue editing it later.

      Website Design Made Simple

      Whether you want to install a WordPress theme, choose a website template, or hire a web developer, we can help! Subscribe to our monthly digest so you never miss an article.

      You Can Be a Website Designer

      Building your business website from scratch should be quick and easy. Fortunately, the intuitive drag-and-drop interface of WP Website Builder and its dozens of professional WordPress themes make it a practical choice for new website owners.

      Ready to build your own website? Get started and have your WordPress site up and running in no time by signing up for one of our shared hosting plans and WP Website Builder!



      Source link