1674849300
Decision-making in Business is one of the most significant aspects of running a business. It involves choosing what products or services to offer, how to price them, where to sell them, and how to promote them. Good decision-making can mean the difference between success and failure for a business.
Good decision-making in business requires careful consideration of all factors involved. This includes understanding the market, understanding consumer needs and wants, understanding your competition, and understanding your strengths and weaknesses. Once all this information has been gathered, you can start making informed decisions about which course of action is the best for your business.
Decision-making in business can affect everything from your products and services to how you manage your finances.
Making decisions can be difficult, but weighing up all the options before settling on a course of action is essential. This guide will help you understand the different types of decision-making and how they can impact your business.
There are three main types of decision-making in business: strategic, operational, and tactical.
Strategic decisions are long-term and usually involve major changes to the direction of your business. They’re typically made by senior management and require careful planning.
Operational decisions are medium-term and usually relate to the day-to-day running of your business. They’re typically made by middle managers and often involve trade-offs between different objectives.
Tactical decisions are short-term and usually relate to specific tasks or projects. They’re typically made by front-line employees and often involve local optimisation rather than global optimisation.
The type of decision you need to make will depend on the situation you’re facing. For example, if you’re launching a new product, you’ll need to make strategic decisions about what market you want to target and what price point you want to set. If you’re managing a team of salespeople, you’ll need to make operational decisions about how best to allocate resources amongst them.
Decision-making is a process that businesses use to identify and select the best course of action to achieve their desired goal. The steps in this process are:
Defining the problem or opportunity is a critical step in any decision-making process. It involves asking questions to identify and understand the issue, its causes and effects, and who or what is affected by it. This helps define the scope of what needs to be addressed and provides an understanding of how big a task lies ahead. Defining the problem also serves as a solid foundation for developing strategies tailored to achieve desired outcomes. Therefore, taking the time upfront to define the problem or opportunity carefully can help ensure success when deciding how best to address it.
It involves researching potential courses of action, evaluating risks and benefits, examining alternative possibilities, and consulting experts. This helps to ensure that decision-makers have adequate data to make informed choices about their organisation’s long-term success. Collecting relevant data includes:
Additionally, gathering input from those affected by a decision can help build consensus around any proposed choice before moving forward – thus limiting surprises down the line.
Also Read: What is Digital Financial Services? Explained
Once you have all the vital information and options, an essential step in the decision-making in the business process is to analyse everything available before moving forward. It involves breaking down data, researching alternatives, and understanding the implications of each option. This allows us to make informed decisions based on facts rather than assumptions or guesses. During this step, it’s essential to consider all aspects of a potential decision, including possible risks and rewards, as well as any ethical issues that may be involved. Analysing information can help ensure we have all relevant details before moving forward with an action plan.
It involves evaluating all options carefully and determining which would provide the most benefit or create the least amount of harm. To select the best option, it’s important to consider data and evidence that support each choice and consult with experts who may have further knowledge about any potential consequences of an action.
Additionally, it’s important to be aware of any potential biases that could influence your decision-making process, such as the personal beliefs or opinions of individuals involved. Ultimately, selecting the best option requires careful thought and consideration before making a final call on what action should be taken.
It involves mapping out a strategy for taking action and ensuring that all steps necessary to complete a project are accounted for. The plan should include objectives, a timeline, resources needed and a budget. In addition, it should also consider potential risks and contingencies as well as how any results will be monitored and evaluated.
A successful plan will help maximise chances of success by minimising wasted time, effort or money while guiding how to proceed when faced with unexpected obstacles or changes. Planning can make all the difference between failure and success when implementing decisions!
Implementing the plan is the final step in the decision-making in a business process. It involves putting into action all of the decisions made throughout the previous steps of planning, analysis and evaluation. The implementation phase requires clear communication among stakeholders, ensuring everyone knows their roles and responsibilities for this stage. Additionally, it is important to track progress to quickly identify and address any changes or adjustments. The implementation also includes monitoring results to ensure goals are met, evaluating what worked well and determining any areas for improvement for plans.
7. Evaluate the results
Evaluating the results of a decision is an important step in the decision-making process. It provides feedback on whether or not the chosen course of action successfully met its desired outcome. Evaluating results can determine if changes need to be made to improve future outcomes or if more resources should be allocated towards achieving success.
Evaluations help to identify what worked and what didn’t, allowing for better-informed decisions further down the line. This can also ensure that potential risks are identified and managed before they become costly. Ultimately, taking time to evaluate the results of a decision will save time and money in the long run by pinpointing areas where improvements can be made quickly and efficiently. This process helps businesses to make sound decisions that will lead to positive outcomes and help them achieve their goals.
Decision-Making Models are tools used to help decision-makers identify, analyse and prioritise potential solutions to a problem. They can help make decisions in both personal and professional contexts. There are several different types of Decision Making Models, including Rational Choice Theory, the Delphi Technique and System Dynamics.
Each model has unique strengths and weaknesses that should be considered when evaluating which option best fits the needs of a particular situation. Ultimately, each Decision-Making in Business Model is designed to provide structure, clarity and guidance during the decision-making process while allowing individuals to remain creative and open-minded in their approach.
The Rational Model of decision-making is a systematic approach to the problem-solving and decision-making process. This model provides a logical, step-by-step method for making decisions that are based on facts and data rather than emotion or bias. The main features of this model include the following:
1) Identification of the Problem: Before making any decisions, it is important to identify and analyse the problem at hand. This involves analysing the situation from multiple perspectives to understand its cause and potential solutions.
2) Gathering Information: Once the problem has been identified, it is essential to gather information about possible solutions through research or consulting experts to determine which solution will work best for the organisation or individual involved.
3) Assessing Alternatives: After collecting data on potential solutions, it is necessary to assess each alternative in terms of cost efficiency and other criteria such as feasibility, effectiveness, etc., so that only those options with positive outcomes are chosen as viable alternatives.
4) Making Decisions: After assessing all available alternatives according to whatever criteria have been set forth by stakeholders, it is time for management or leadership personnel responsible for deciding upon a course of action must come together and make an informed choice that takes into account both rational analysis as well as personal preferences before finalising their selection.
Benefits associated with using this type of decision-making model include the following:
An intuitive decision-making model is a type of decision-making model which relies heavily on intuition and gut feelings. It is often used when making high-risk decisions or involving complex data with many variables.
The main feature of the intuitive decision-making model is its reliance on instinct to make decisions, rather than traditional analytical approaches that rely mainly on facts and data. This allows users to draw upon their personal experiences, values and beliefs to devise creative solutions for difficult situations. Consequently, this type of decision-making is suitable for scenarios where there may not be enough reliable information available, or the situation requires creativity due to its complexity.
Another key benefit of the intuitive decision-making model is that it can provide users with an immediate response, allowing them to react quickly in uncertain or fast-paced environments such as emergencies or markets requiring rapid responses from investors. Additionally, unlike more analytical models, which require substantial time commitments from users, an intuitive approach can allow individuals to make quick judgments without being bogged down by excessive research and analysis processes.
Despite these advantages, there are certain drawbacks associated with using an intuitive decision-making model, including potential bias due to personal experiences influencing outcomes as well as a possible oversimplification of complex problems leading to less optimal results than if more effort had been put into researching all angles before coming up with a solution (ease trap).
Furthermore, since this kind of approach generally does not consider external factors such as market trends etc., it should only be used when other sources cannot provide comprehensive enough insights into what would constitute a successful outcome for any given problem/solution scenario (could also increase risks associated with implementing said solution).
In conclusion, while the use of Intuitive Decision-Making in Business Models has several benefits, such as providing quick responses when needed and encouraging creative thinking – it must still be used cautiously alongside other forms of analysis so that any potentially damaging constraints may be taken into account before finalising any decisions made based upon this method alone.
The Vroom–Yetton model is a decision-making business model designed to help managers make decisions about how best to approach a particular problem. Victor Vroom and Phillip Yetton developed it in 1973. The model provides guidance for managers on selecting an appropriate leadership style based on the amount of involvement or participation desired from their subordinates and the level of uncertainty associated with the situation at hand.
The basic idea behind the Vroom–Yetton Model is that different levels of decision-making require different management styles and involvements – such as autocratic (leader makes all decisions) vs democratic (all members participate). This means that when faced with a difficult decision, it can be beneficial for leaders to consider which style would work best given the available information and resources and what goals they are trying to achieve.
The primary benefit of using this decision-making process is that it allows leaders to assess situations better before choosing an action plan. This helps them avoid making hasty decisions without considering other factors like group dynamics or potential outcomes. Additionally, because this method encourages open communication between team members during discussions surrounding essential topics, there is less chance for misunderstandings or disagreements down the line regarding who made what choices or why those selections were made in the first place.
Considering each person’s experience and expertise when deciding upon an action plan instead of relying solely on one individual’s opinion allows for more balanced opinions, which may result in better outcomes overall than if one single voice had been relied upon without further investigation into others’ perspectives. This increases efficiency since everyone involved feels heard while still allowing efficient time decisions due to having already outlined parameters of various options within several predetermined models before commencing discussion around hypothetical courses of action – reducing wasted time debating issues outside the scope that could have been addressed beforehand through proper use pre-established models such as Vroom-Yetton’s.
Utilising a framework like Vroom–Yetton Model can be beneficial in helping teams come up with practical solutions quickly while still ensuring all voices are considered carefully before any conclusions are drawn. By considering multiple perspectives throughout each step and understanding exactly what kind of managerial approach should be taken depending on current circumstances, collective wisdom can ensure optimal results over-relying on one individual alone whenever complex problems arise, requiring rapid yet thoughtful resolutions.
The Recognition Primed Decision (RPD) model is a type of decision-making in a business model that relies on the recognition and experience of an individual to make decisions. Developed by Gary Klein, this model focuses on recognising patterns in situations that can help people make quick decisions without having to analyse or process data. This method is based on the belief that experienced professionals do not need detailed information or analysis when making decisions; instead, they can draw upon their previous experiences and recognise similarities between them and the current situation to come up with a good solution quickly.
One advantage of using the RPD model is its speedy nature: it helps individuals rapidly assess different options and determine the most effective given their current situation. Additionally, because it relies heavily on personal experience, this method allows for more creativity than traditional analytical approaches, as it encourages individuals to think outside the box when solving problems. Furthermore, since this approach does not require extensive amounts of data collection or processing time, it allows for quicker implementation of solutions.
Another benefit provided by RPD models is that they encourage collaboration among professionals who have similar experiences and knowledge bases through sharing stories about how they handled similar challenges in other contexts. This provides an opportunity for team members to compare notes while also building trust within teams due to improved communication processes. Additionally, such collaborative activities help strengthen relationships between individuals and organisations involved in projects where multiple parties must work together efficiently towards achieving the same goal(s).
Finally, another benefit offered by utilising RPD models is that these methods can easily be adapted according to contextual changes since each situation will present unique opportunities for problem-solving; thus allowing users to implement versatile strategies depending on what fits best with changing conditions at hand. In addition, such flexible approaches are beneficial for those working under tight deadlines since there will likely be less wasted energy due to fewer errors from wrong assumptions being made priorly.
Overall, recognition-primed decision-making models enable faster response times and ensure accurate results. The experiential nature helps enhance collaborative efforts amongst professionals with similar knowledgebases while providing efficient solutions regardless of circumstantial changes. Thus, this method offers a reliable and beneficial approach to problem-solving and decision-making.
Bounded Rationality Model
The bounded rationality model is decision-making in the business model based on the idea that humans are limited in their ability to make decisions due to time, information and cognitive constraints. This model suggests that people do not always have access to all of the facts or have enough time or resources to weigh up all potential options before making a choice. Instead, they rely on intuition, heuristics and their own experiences when making decisions.
The main benefit of the bounded rationality approach is that it explains why non-optimal choices are often made instead of purely rational ones. It considers how human psychology affects our decision-making processes and reflects real-life situations more accurately than traditional models that assume perfect knowledge and unlimited resources. Additionally, this model allows us to account for ‘irrational’ behaviour such as risk aversion or loss aversion – behaviours which cannot be explained by pure rational analysis alone but can still be observed in practice.
Adopting a bounded rationality approach also has implications for policy design; rather than trying to achieve ideal outcomes through complicated rules or regulations, policies should consider peoples’ limitations when it comes to understanding complex systems or weighing up multiple options to produce better results overall.
Finally, since this approach recognises the role played by emotions and personal biases when making decisions, it helps us understand how these factors can influence individual behaviour even if they don’t necessarily lead them towards an optimal outcome – something which could help inform strategies like marketing campaigns where companies need insight into what drives consumer preferences over specific products/services etc.
In conclusion, the bounded rationality model offers valuable insights into how people behave when faced with difficult decisions due to its focus on psychological aspects such as intuition and emotion as well as practical limitations like time constraints or lack of information – allowing us both to understand irrational behaviour better but also helping improve policy design so that solutions are tailored towards actual user needs rather than theoretical ideals.
Decision-making in business is an essential activity for any organisation. It involves analysing available data and options, weighing the merits and drawbacks of the options, and choosing the best course of action to achieve desired results. By clearly understanding decision-making processes, businesses can make better decisions based on sound information and research that will lead to improved performance. This includes increasing profits, enhancing customer satisfaction, reducing costs or improving operational efficiency. Ultimately, effective decision-making leads to tremendous success for the company as a whole.
The Executive Development Programme in General Management course is an important resource for helping business professionals understand the importance of decision-making. This comprehensive programme provides detailed instruction on how to develop a strategic approach towards problem-solving, analyse issues through research and data analysis, and effectively engage stakeholders throughout the process. Additionally, it offers guidance on making ethical and financially sound decisions while considering long-term implications for the company’s success. With this knowledge, executives can become more confident when making key business decisions that will have lasting impacts on their organisation.
Original article source at: https://www.edureka.co/
1672813407
In Machine Learning, concept learning can be termed as “a problem of searching through a predefined space of potential hypothesis for the hypothesis that best fits the training examples” – Tom Mitchell. In this article, we will go through one such concept learning algorithm known as the Find-S algorithm. If you want to go beyond this article and really want the level of expertise in you – you can get certified in Machine Learning with Python Certification!
In order to understand Find-S algorithm, you need to have a basic idea of the following concepts as well:
1. Concept Learning
Let’s try to understand concept learning with a real-life example. Most of human learning is based on past instances or experiences. For example, we are able to identify any type of vehicle based on a certain set of features like make, model, etc., that are defined over a large set of features.
These special features differentiate the set of cars, trucks, etc from the larger set of vehicles. These features that define the set of cars, trucks, etc are known as concepts.
Similar to this, machines can also learn from concepts to identify whether an object belongs to a specific category or not. Any algorithm that supports concept learning requires the following:
If you want to learn AI-ML in-depth, come to us and sign up for this Post Graduate Diploma Artificial Intelligence Online Course at Edureka.
2. General Hypothesis
Hypothesis, in general, is an explanation for something. The general hypothesis basically states the general relationship between the major variables. For example, a general hypothesis for ordering food would be I want a burger.
G = { ‘?’, ‘?’, ‘?’, …..’?’}
3. Specific Hypothesis
The specific hypothesis fills in all the important details about the variables given in the general hypothesis. The more specific details into the example given above would be I want a cheeseburger with a chicken pepperoni filling with a lot of lettuce.
S = {‘Φ’,’Φ’,’Φ’, ……,’Φ’}
Now ,let’s talk about the Find-S Algorithm in Machine Learning.
The Find-S algorithm follows the steps written below:
Now that we are done with the basic explanation of the Find-S algorithm, let us take a look at how it works.
Find out our Machine Learning Certification Training Course in Top Cities
There are a few limitations of the Find-S algorithm listed down below:
Now that we are aware of the limitations of the Find-S algorithm, let us take a look at a practical implementation of the Find-S Algorithm.
To understand the implementation, let us try to implement it to a smaller data set with a bunch of examples to decide if a person wants to go for a walk.
The concept of this particular problem will be on what days does a person likes to go on walk.
Time | Weather | Temperature | Company | Humidity | Wind | Goes |
Morning | Sunny | Warm | Yes | Mild | Strong | Yes |
Evening | Rainy | Cold | No | Mild | Normal | No |
Morning | Sunny | Moderate | Yes | Normal | Normal | Yes |
Evening | Sunny | Cold | Yes | High | Strong | Yes |
Looking at the data set, we have six attributes and a final attribute that defines the positive or negative example. In this case, yes is a positive example, which means the person will go for a walk.
So now, the general hypothesis is:
h0 = {‘Morning’, ‘Sunny’, ‘Warm’, ‘Yes’, ‘Mild’, ‘Strong’}
This is our general hypothesis, and now we will consider each example one by one, but only the positive examples.
h1= {‘Morning’, ‘Sunny’, ‘?’, ‘Yes’, ‘?’, ‘?’}
h2 = {‘?’, ‘Sunny’, ‘?’, ‘Yes’, ‘?’, ‘?’}
We replaced all the different values in the general hypothesis to get a resultant hypothesis. Now that we know how the Find-S algorithm works, let us take a look at an implementation using Python.
Let’s try to implement the above example using Python. The code to implement the Find-S algorithm using the above data is given below.
import pandas as pd
import numpy as np
#to read the data in the csv file
data = pd.read_csv("data.csv")
print(data,"n")
#making an array of all the attributes
d = np.array(data)[:,:-1]
print("n The attributes are: ",d)
#segragating the target that has positive and negative examples
target = np.array(data)[:,-1]
print("n The target is: ",target)
#training function to implement find-s algorithm
def train(c,t):
for i, val in enumerate(t):
if val == "Yes":
specific_hypothesis = c[i].copy()
break
for i, val in enumerate(c):
if t[i] == "Yes":
for x in range(len(specific_hypothesis)):
if val[x] != specific_hypothesis[x]:
specific_hypothesis[x] = '?'
else:
pass
return specific_hypothesis
#obtaining the final hypothesis
print("n The final hypothesis is:",train(d,target))
Output:
This brings us to the end of this article where we have learned the Find-S Algorithm in Machine Learning with its implementation and use case. I hope you are clear with all that has been shared with you in this tutorial.
Are you wondering how to advance once you know the basics of what Machine Learning is? Take a look at Edureka’s Machine Learning Python Certification, which will help you get on the right path to succeed in this fascinating field. Learn the fundamentals of Machine Learning, machine learning steps and methods that include unsupervised and supervised learning, mathematical and heuristic aspects, and hands-on modeling to create algorithms. You will be prepared for the position of Machine Learning engineer.
You can also take a Machine Learning Course Masters Program. The program will provide you with the most in-depth and practical information on machine-learning applications in real-world situations. Additionally, you’ll learn the essentials needed to be successful in the field of machine learning, such as statistical analysis, Python, and data science.
We are here to help you with every step on your journey and come up with a curriculum that is designed for students and professionals who want to be a Machine Learning Engineer. The course is designed to give you a head start into Python programming and train you for both core and advanced Python concepts along with various Machine learning Algorithms like SVM, Decision Tree, etc.
If you come across any questions, feel free to ask all your questions in the comments section of “Find-S Algorithm In Machine Learning” and our team will be glad to answer.
Machine Learning Course lets you master the application of AI with the expert guidance. It includes various algorithms with applications.
Original article source at: https://www.edureka.co/
1670066845
The idea behind single page applications (SPA) is to create a smooth browsing experience like the one found in native desktop apps. All of the necessary code for the page is loaded only once and its content gets changed dynamically through JavaScript. If everything is done right the page shouldn't ever reload, unless the user refreshes it manually.
There are many frameworks for single page applications out there. First we had Backbone, then Angular, now React. It takes a lot of work to constantly learn and re-learn things (not to mention having to support old code you've written in a long forgotten framework). In some situations, like when your app idea isn't too complex, it is actually not that hard to create a single page app without using any external frameworks. Here is how to do it.
Note: To run this example after downloading it, you need a locally running webserver like Apache. Our demo uses AJAX so it will not work if you simply double-click index.html for security reasons.
We will not be using a framework, but we will be using two libraries - jQuery for DOM manipulation and event handling, and Handlebars for templates. You can easily omit these if you wish to be even more minimal, but we will use them for the productivity gains they provide. They will be here long after the hip client-side framework of the day is forgotten.
The app that we will be building fetches product data from a JSON file, and displays it by rendering a grid of products with Handlebars. After the initial load, our app will stay on the same URL and listen for changes to the hash part with the hashchange event. To navigate around the app, we will simply change the hash. This has the added benefit that browser history will just work without extra effort on our part.
Our project's folder
As you can see there isn't much in our project folder. We have the regular web app setup - HTML, JavaScript and CSS files, accompanied by a products.json containing data about the products in our shop and a folder with images of the products.
The .json file is used to store data about each product for our SPA. This file can easily be replaced by a server-side script to fetch data from a real database.
[
{
"id": 1,
"name": "Sony Xperia Z3",
"price": 899,
"specs": {
"manufacturer": "Sony",
"storage": 16,
"os": "Android",
"camera": 15
},
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tristique ipsum in efficitur pharetra. Maecenas luctus ante in neque maximus, sed viverra sem posuere. Vestibulum lectus nisi, laoreet vel suscipit nec, feugiat at odio. Etiam eget tellus arcu.",
"rating": 4,
"image": {
"small": "/images/sony-xperia-z3.jpg",
"large": "/images/sony-xperia-z3-large.jpg"
}
},
{
"id": 2,
"name": "Iphone 6",
"price": 899,
"specs": {
"manufacturer": "Apple",
"storage": 16,
"os": "iOS",
"camera": 8
},
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tristique ipsum in efficitur pharetra. Maecenas luctus ante in neque maximus, sed viverra sem posuere. Vestibulum lectus nisi, laoreet vel suscipit nec, feugiat at odio. Etiam eget tellus arcu.",
"rating": 4,
"image": {
"small": "/images/iphone6.jpg",
"large": "/images/iphone6-large.jpg"
}
}
]
In our html file we have several divs sharing the same class "page". Those are the different pages (or as they are called in SPA - states) our app can show. However, on page load all of these are hidden via CSS and need the JavaScript to show them. The idea is that only one page can be visible at a time and our script is the one to decide which one it is.
<div class="main-content">
<div class="all-products page">
<h3>Our products</h3>
<div class="filters">
<form>
Checkboxes here
</form>
</div>
<ul class="products-list">
<script id="products-template" type="x-handlebars-template">
{{#each this}}
<li data-index="{{id}}">
<a href="#" class="product-photo"><img src="{{image.small}}" height="130" alt="{{name}}"/></a>
<h2><a href="#"> {{name}} </a></h2>
<ul class="product-description">
<li><span>Manufacturer: </span>{{specs.manufacturer}}</li>
<li><span>Storage: </span>{{specs.storage}} GB</li>
<li><span>OS: </span>{{specs.os}}</li>
<li><span>Camera: </span>{{specs.camera}} Mpx</li>
</ul>
<button>Buy Now!</button>
<p class="product-price">{{price}}$</p>
<div class="highlight"></div>
</li>
{{/each}}
</script>
</ul>
</div>
<div class="single-product page">
<div class="overlay"></div>
<div class="preview-large">
<h3>Single product view</h3>
<img src=""/>
<p></p>
<span class="close">×</span>
</div>
</div>
<div class="error page">
<h3>Sorry, something went wrong :(</h3>
</div>
</div>
We have three pages: all-products (the product listing), single-product (the individual product page) and error.
The all-products page consists of a title, a form containing checkboxes for filtering and a <ul> tag with the class "products-list". This list is generated with handlebars using the data stored in products.json, creating a <li> for each entry in the json. Here is the result:
The Products
Single-product is used to show information about only one product. It is empty and hidden on page load. When the appropriate hash address is reached, it is populated with product data and shown.
The error page consist of only an error message to let you know when you've reached a faulty address.
First, lets make a quick preview of the functions and what they do.
$(function () {
checkboxes.click(function () {
// The checkboxes in our app serve the purpose of filters.
// Here on every click we add or remove filtering criteria from a filters object.
// Then we call this function which writes the filtering criteria in the url hash.
createQueryHash(filters);
});
$.getJSON( "products.json", function( data ) {
// Get data about our products from products.json.
// Call a function that will turn that data into HTML.
generateAllProductsHTML(data);
// Manually trigger a hashchange to start the app.
$(window).trigger('hashchange');
});
$(window).on('hashchange', function(){
// On every hash change the render function is called with the new hash.
// This is how the navigation of our app happens.
render(decodeURI(window.location.hash));
});
function render(url) {
// This function decides what type of page to show
// depending on the current url hash value.
}
function generateAllProductsHTML(data){
// Uses Handlebars to create a list of products using the provided data.
// This function is called only once on page load.
}
function renderProductsPage(data){
// Hides and shows products in the All Products Page depending on the data it recieves.
}
function renderSingleProductPage(index, data){
// Shows the Single Product Page with appropriate data.
}
function renderFilterResults(filters, products){
// Crates an object with filtered products and passes it to renderProductsPage.
renderProductsPage(results);
}
function renderErrorPage(){
// Shows the error page.
}
function createQueryHash(filters){
// Get the filters object, turn it into a string and write it into the hash.
}
});
Remember that the concept of SPA is to not have any loads going on while the app is running. That's why after the initial page load we want to stay on the same page, where everything we need has already been fetched by the server.
However, we still want to be able to go somewhere in the app and, for example, copy the url and send it to a friend. If we never change the app's address they will just get the app the way it looks in the beginning, not what you wanted to share with them. To solve this problem we write information about the state of the app in the url as #hash. Hashes don't cause the page to reload and are easily accessible and manipulated.
On every hashchange we call this:
function render(url) {
// Get the keyword from the url.
var temp = url.split('/')[0];
// Hide whatever page is currently shown.
$('.main-content .page').removeClass('visible');
var map = {
// The Homepage.
'': function() {
// Clear the filters object, uncheck all checkboxes, show all the products
filters = {};
checkboxes.prop('checked',false);
renderProductsPage(products);
},
// Single Products page.
'#product': function() {
// Get the index of which product we want to show and call the appropriate function.
var index = url.split('#product/')[1].trim();
renderSingleProductPage(index, products);
},
// Page with filtered products
'#filter': function() {
// Grab the string after the '#filter/' keyword. Call the filtering function.
url = url.split('#filter/')[1].trim();
// Try and parse the filters object from the query string.
try {
filters = JSON.parse(url);
}
// If it isn't a valid json, go back to homepage ( the rest of the code won't be executed ).
catch(err) {
window.location.hash = '#';
}
renderFilterResults(filters, products);
}
};
// Execute the needed function depending on the url keyword (stored in temp).
if(map[temp]){
map[temp]();
}
// If the keyword isn't listed in the above - render the error page.
else {
renderErrorPage();
}
}
This function takes into consideration the beginning string of our hash, decides what page needs to be shown and calls the according functions.
For example if the hash is '#filter/{"storage":["16"],"camera":["5"]}', our codeword is '#filter'. Now the render function knows we want to see a page with the filtered products list and will navigate us to it. The rest of the hash will be parsed into an object and a page with the filtered products will be shown, changing the state of the app.
This is called only once on start up and turns our JSON into actual HTML5 content via handlebars.
function generateAllProductsHTML(data){
var list = $('.all-products .products-list');
var theTemplateScript = $("#products-template").html();
//Compile the template
var theTemplate = Handlebars.compile (theTemplateScript);
list.append (theTemplate(data));
// Each products has a data-index attribute.
// On click change the url hash to open up a preview for this product only.
// Remember: every hashchange triggers the render function.
list.find('li').on('click', function (e) {
e.preventDefault();
var productIndex = $(this).data('index');
window.location.hash = 'product/' + productIndex;
})
}
This function receives an object containing only those products we want to show and displays them.
function renderProductsPage(data){
var page = $('.all-products'),
allProducts = $('.all-products .products-list > li');
// Hide all the products in the products list.
allProducts.addClass('hidden');
// Iterate over all of the products.
// If their ID is somewhere in the data object remove the hidden class to reveal them.
allProducts.each(function () {
var that = $(this);
data.forEach(function (item) {
if(that.data('index') == item.id){
that.removeClass('hidden');
}
});
});
// Show the page itself.
// (the render function hides all pages so we need to show the one we want).
page.addClass('visible');
}
Shows the single product preview page:
function renderSingleProductPage(index, data){
var page = $('.single-product'),
container = $('.preview-large');
// Find the wanted product by iterating the data object and searching for the chosen index.
if(data.length){
data.forEach(function (item) {
if(item.id == index){
// Populate '.preview-large' with the chosen product's data.
container.find('h3').text(item.name);
container.find('img').attr('src', item.image.large);
container.find('p').text(item.description);
}
});
}
// Show the page.
page.addClass('visible');
}
Takes all the products, filters them based on our query and returns an object with the results.
function renderFilterResults(filters, products){
// This array contains all the possible filter criteria.
var criteria = ['manufacturer','storage','os','camera'],
results = [],
isFiltered = false;
// Uncheck all the checkboxes.
// We will be checking them again one by one.
checkboxes.prop('checked', false);
criteria.forEach(function (c) {
// Check if each of the possible filter criteria is actually in the filters object.
if(filters[c] && filters[c].length){
// After we've filtered the products once, we want to keep filtering them.
// That's why we make the object we search in (products) to equal the one with the results.
// Then the results array is cleared, so it can be filled with the newly filtered data.
if(isFiltered){
products = results;
results = [];
}
// In these nested 'for loops' we will iterate over the filters and the products
// and check if they contain the same values (the ones we are filtering by).
// Iterate over the entries inside filters.criteria (remember each criteria contains an array).
filters[c].forEach(function (filter) {
// Iterate over the products.
products.forEach(function (item){
// If the product has the same specification value as the one in the filter
// push it inside the results array and mark the isFiltered flag true.
if(typeof item.specs[c] == 'number'){
if(item.specs[c] == filter){
results.push(item);
isFiltered = true;
}
}
if(typeof item.specs[c] == 'string'){
if(item.specs[c].toLowerCase().indexOf(filter) != -1){
results.push(item);
isFiltered = true;
}
}
});
// Here we can make the checkboxes representing the filters true,
// keeping the app up to date.
if(c && filter){
$('input[name='+c+'][value='+filter+']').prop('checked',true);
}
});
}
});
// Call the renderProductsPage.
// As it's argument give the object with filtered products.
renderProductsPage(results);
}
Shows the error state:
function renderErrorPage(){
var page = $('.error');
page.addClass('visible');
}
Stringifies the filters object and writes it into the hash.
function createQueryHash(filters){
// Here we check if filters isn't empty.
if(!$.isEmptyObject(filters)){
// Stringify the object via JSON.stringify and write it after the '#filter' keyword.
window.location.hash = '#filter/' + JSON.stringify(filters);
}
else{
// If it's empty change the hash to '#' (the homepage).
window.location.hash = '#';
}
}
Single page applications are perfect when you want give your project a more dynamic and fluid feel, and with the help of some clever design choices you can offer your visitors a polished, pleasant experience.
Original article source at: https://tutorialzine.com/
1593332340
See why Umur Cubukcu’s team is on a mission to make Azure the best destination to run Postgres. From acquiring the Postgres company Citus Data, to enabling a
#making #azure #destination #postgres #microsoft #european virtual open