ES6 MVC JavaScript教程:构建简单的CRUD应用

In this ES6 MVC JavaScript tutorial, you’re going to learn how to build a simple CRUD app using ES6 Class.

在此ES6 MVC JavaScript教程中,您将学习如何使用ES6类构建简单的CRUD应用。

步骤01:设置项目 (STEP 01: Setting Up The Project)

Here is the Address Book Project setup. It has just three simple files: HTML, CSS and JS.

这是通讯簿项目设置。 它只有三个简单的文件:HTML,CSS和JS。

1. Create a folder structure.

1.创建一个文件夹结构。

| AddressBook (folder) 
| -- index.html
| -- app.js
| -- style.css

2. Link style.css and app.js file to the index.html file.

2.将style.css和app.js文件链接到index.html文件。

<!DOCTYPE html>
<html>
<head>
<title>Address Book - How to write testable javascript code</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head><body>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

3. Create a contact list module inside index.html where all of the contacts will be.

3.在index.html中创建所有联系人所在的联系人列表模块。

<body>
<h2>Address Book</h2><!-- contact list module -->
<section>
<ul id="contact-list">
loading...
</ul>
</section>
</body>

2.创建一个MVC结构 (2. Create An MVC Structure)

模型 (Model)

Add some Model Data which is the M part of MVC inside app.js. This could be a separate class fetching data from API via AJAX call.

在app.js中添加一些模型数据,这是MVC的M部分。 这可能是一个单独的类,可通过AJAX调用从API提取数据。

For simplicity sake, I have made a simple array of objects called contactsData.

为了简单起见,我制作了一个简单的对象数组,称为contactsData

// ============== Model =========================
const contactsData = [
{
fname: "Anbu",
lname: "Arasan",
phone: "190-309-6101",
email: "anbu.arasan@email.com",
},
{
fname: "Arivu",
lname: "Mugilan",
phone: "490-701-7102",
email: "arivu.mugilan@email.com",
},
{
fname: "Bob",
lname: "Johnson",
phone: "574-909-3948",
email: "bob.johnson@email.com",
},
{
fname: "Raja",
lname: "Tamil",
phone: "090-909-0101",
email: "raja.tamil@email.com",
},
{
fname: "Sundar",
lname: "Kannan",
phone: "090-909-0101",
email: "sundar.kannan@email.com",
},
];

视图 (View)

1. Create a class name AddressBookView inside app.js which is the V (view) part of MVC. Add an init() method in it.

1.在app.js内创建一个类名AddressBookView ,它是MVC的V(视图)部分。 在其中添加一个init()方法。

// ============== View =========================
class AddressBookView {
init() {
console.log("render HTML here");
}
}

2. Define theaddressBookView object by instantiating theAddressBookView class.

2.通过实例化AddressBookView类来定义addressBookView对象。

const addressBookView = new AddressBookView();

控制者 (Controller)

1. Declare a class called AddressBookCtrl which will be the controller.

1.声明一个名为AddressBookCtrl ,它将作为控制器

The rule of thumb is, the Model and View can never talk to each other directly and the controller is the only one that should communicate to both of them.

经验法则是,“ 模型”和“ 视图”永远不能直接相互通信,并且控制器是唯一应与两者通信的控制器

//================ Controller ==================
class AddressBookCtrl {
constructor(addressBookView) {
this.addressBookView = addressBookView;
}
init() {
this.addressBookView.init();
}
}

2. Make an addressBookCtrl object by instantiating theAddressBookCtrl class and pass the addressBookView object as an argument to it like so. (Dependency Injection)

2.一个addressBookCtrl通过实例化对象AddressBookCtrl类并传递addressBookView对象作为参数传递给它像这样。 (依赖注入)

const addressBookApp = new AddressBookCtrl(addressBookView);

3. Start the application by invoking theinit() method on addressBookApp.

3.通过在addressBookApp上调用init()方法来启动应用程序。

addressBookApp.init();

When theaddressBookApp.init() method is invoked, the addressBookView.init() method will be fired and we will see the output message render HTML here on the browser console.

addressBookApp.init()方法被调用时,addressBookView .init()方法将被解雇,我们将看到输出的消息呈现HTML这里的浏览器控制台上。

At this stage, you have successfully hooked the Controller and View. 🙂

在此阶段,您已成功钩住Controller和View。 🙂

3.获取所有联系人的视图 (3. Get All Contacts To The View)

1. Get all the model data by declaring thegetContacts() method inside theAddressBookCtrl class.

1.通过在AddressBookCtrl类内声明getContacts()方法来获取所有模型数据。

getContacts() {
return contactsData;
}

2. Declare renderContactListModule().

2.声明renderContactListModule()。

renderContactListModule() {
//get all contacts and assign to contacts
const contacts = addressBookApp.getContacts();// cache #contact-list DOM
const $contactListUI = document.getElementById('contact-list');// clear HTML from the DOM
$contactListUI.innerHTML = '';for (let i = 0, len = contacts.length; i < len; i++) {
let $li = document.createElement('li');
$li.setAttribute('class', 'contact-list-item');
$li.setAttribute('data-index', i);
$li.innerHTML = `${contacts[i]['fname']},${contacts[i]['lname']}`;
$contactListUI.append($li);
}
}

Inside therenderContactListModule() method, get the model data by invoking the getContacts() method on addressBookApp.

renderContactListModule()方法内部,通过在addressBookApp上调用getContacts()方法来获取模型数据。

Then, get a DOM reference to the contact list element and store it in $contactListUI.

然后,获取对联系人列表元素的DOM引用,并将其存储在$ contactListUI中。

After that, clear HTML from the $contactListUI if there were any previously.

之后,从$ contactListUI清除HTML(如果以前有)。

Loop through the model data and create li element inside it and set two attributes to it, which are class and data-index.

遍历模型数据并在其中创建li元素,并为其设置两个属性,即class和data-index。

The value of the data-index attribute holds an incremental integer on every iteration.

data-index属性的值在每次迭代时都保留一个增量整数。

Finally, set the actual first name and last name data to the list item using an HTML property and append li to ul.

最后,使用HTML属性将实际的名字和姓氏数据设置到列表项,并将li附加到ul。

3. Invoke renderContactListModule().

3.调用renderContactListModule()。

Call the renderContactListModule() inside the addressBookView.init()method.

addressBookView.init()方法内调用renderContactListModule()。

init() {
this.renderContactListModule();
}

At this stage, you will be able to see all of the contacts on the browser.

在此阶段,您将能够在浏览器上看到所有联系人。

4.获取选定的联系人 (4. Get Selected Contact)

1. Add the contact details module HTML code in theindex.html file.

1.在index.html文件中添加联系人详细信息模块HTML代码。

<!-- contact item details module   -->
<section>
<div id="contact-item-details">loading...</div>
</section>

2. Go back to app.js and add an event listener to the <li> element inside the renderContactListModule() method before appending <li> to <ul>.

2.返回到app.js然后将事件侦听器添加到renderContactListModule()方法内的<li>元素中,然后再将<li>附加到<ul>

$li.addEventListener("click", this.renderContactDetailsModule);

3. Define therenderContactDetailsModule() callback function insidethe AddressBookView class.

3.在AddressBookView类中定义renderContactDetailsModule()回调函数。

renderContactDetailsModule(e) {
let selectedIndex = null;
if (typeof e === 'object') {
e.stopPropagation();
selectedIndex = this.getAttribute('data-index')
} else {
selectedIndex = e;
}}

To make this call back function more accessible, define selectedIndex and set its initial value to null.

为了使此回调函数更易于访问,请定义selectedIndex并将其初始值设置为null。

Check to see how the callback is called, either click event or just invoke it from somewhere using typeof. If it’s an object, then it’s being called by a click event.

检查一下如何调用回调,无论是单击事件还是仅使用typeof从某个地方调用它。 如果它是一个对象,则由click事件调用。

In that case, get the value of the data-index attribute from the clicked li and assign it to the selectedIndex.

在这种情况下,请从单击的li中获取data-index属性的值,并将其分配给selectedIndex。

If the e parameter is an object, you will need to use e.stopPropagation() in order to avoid event bubbling.

如果e参数是一个对象,则需要使用e.stopPropagation()以避免事件冒泡。

The stopPropagation() will prevent a parent click event when a child click event is triggered.

当触发子点击事件时,stopPropagation()将阻止父点击事件。

Later, we will be adding a couple of child elements like edit and delete buttons inside li. At that time, we do not want to parent click event trigger (li) when we click the child click event (edit button).

稍后,我们将在li内部添加几个子元素,例如“编辑”和“删除”按钮。 那时,当我们单击子级单击事件(编辑按钮)时,我们不希望父级单击事件触发器(li)。

4. Add the getContact() method to our AddressBookCtrl class.

4.将getContact()方法添加到我们的AddressBookCtrl类中。

getContact(index) {
return contactsData[index];
}

This function simply takes an index value and get returns the object from the contactsData based on the index value.

此函数仅获取索引值,并根据索引值从contactsData返回对象。

5. Get selected item using getContact() inside the renderContactDetailsModule().

5.使用renderContactDetailsModule()中的getContact()获取所选项目。

const selectedItem = addressBookApp.getContact(selectedIndex);

6. Obtain the DOM reference for the details view and set the selected items data to it inside the renderContactDetailsModule() as well.

6.获取详细信息视图的DOM引用,并在renderContactDetailsModule()中将所选项目数据设置为其。

const $ContactItemUI = document.getElementById("contact-item-details");

At this stage, the renderContactDetailsModule() function should look like this:

在此阶段,renderContactDetailsModule()函数应如下所示:

renderContactDetailsModule(e) {
let selectedIndex = null;
if (typeof e === 'object') {
e.stopPropagation();
selectedIndex = this.getAttribute('data-index')
} else {
selectedIndex = e;
}const selectedItem = addressBookApp.getContact(selectedIndex);
const $ContactItemUI = document.getElementById('contact-item-details');
$ContactItemUI.innerHTML = `${selectedItem['fname']} <br> ${selectedItem['lname']} <br> ${selectedItem['phone']} <br> ${selectedItem['email']}`;}

7. Add the CSS rule for the details element inside style.css.

7.在style.css中为details元素添加CSS规则。

/* Contact Item Details Module */
#contact-item-details {
float: left;
width: 200px;
background: #333;
overflow: auto;
color: white;
padding: 10px;
margin-left: 1px;
}

8. Highlight the selected item by declaring hightlightCurrentListItem() inside the AddressBookView class.

8.通过在AddressBookView类内声明hightlightCurrentListItem()突出显示选定的项目。

hightlightCurrentListItem(selectedIndex) {
const $ContactListItems = document.getElementsByClassName('contact-list-item');
for (let i = 0, len = $ContactListItems.length; i < len; i++) {
$ContactListItems[i].classList.remove('active');
}
$ContactListItems[selectedIndex].classList.add("active")
}

Invoke it inside the renderContactDetailsModule(e) function.

在renderContactDetailsModule(e)函数中调用它。

That should do it!

那应该做!

5.添加新联系人 (5. Add A New Contact)

1. Create a <section> element with an id=”add-contact-module“ inside the index.html file. This element is going to have ALL the HTML code that belongs to the Add Contact Module.

1.在index.html文件中创建一个id为“ add-contact-module ”的<section>元素。 该元素将具有属于“添加联系人模块”的所有HTML代码。

<section id="add-contact-module">
</section>

Then, add two elements inside it. The first one is an add button and the second one is an add a contact form.

然后,在其中添加两个元素。 第一个是添加按钮,第二个是添加联系人表单。

<section id="add-contact-module">
<button id="open-add-contact-form-btn">+</button>
<form>
<h2>Add Contact</h2>
first name:<br />
<input type="text" data-key="fname" class="add-contact-input" /><br />
last name:<br />
<input type="text" data-key="lname" class="add-contact-input" /><br />
phone:<br />
<input type="text" data-key="phone" class="add-contact-input" /><br />
email:<br />
<input type="text" data-key="email" class="add-contact-input" /><br />
<button type="button" id="add-contact-btn">add</button>
</form>
</section>

2. Add the CSS code inside style.css which will open up the add contact form when mousing over the add contact button.

2.将CSS代码添加到style.css中,当将鼠标悬停在“添加联系人”按钮上时,将打开“添加联系人”表单。

#add-contact-module {
display: inline-block;
margin-bottom: 1px;
margin-left: 8px;
}#add-contact-module #open-add-contact-form-btn {
background: #54bb7d;
font-size: 1.5em;
color: white;
padding-bottom: 5px;
}#add-contact-module form {
position: absolute;
padding: 10px;
width: 150px;
background-color: #e1e1e1;
border: 1px solid #999;
display: none;
}#add-contact-module form input {
width: 97%;
margin: 2px 0;
}#add-contact-module form button {
background: #54bb7d;
font-size: 1em;
padding: 0px 10px;
color: white;
margin-top: 10px;
}#add-contact-module:hover form {
display: block;
}

3. The addContact() method will take the new contact object from the View and push it to the contactsData model array.

3. addContact()方法将从视图中获取新的联系人对象,并将其推入contactsData模型数组。

// ============== Controller (API) =========================class AddressBookCtrl {    constructor(addressBookView) {
this.addressBookView = addressBookView;
} init() {
this.addressBookView.init();
} getContacts() {
return contactsData;
} getContact(index) {
return contactsData[index];
} addContact(contact) {
contactsData.push(contact);
}}

4. Declare the addContactModule() inside the AddressBookView class.

4.在AddressBookView类中声明addContactModule()。

addContactModule() {
const $addContact = document.getElementById('add-contact-btn');
$addContact.addEventListener("click", this.addContactBtnClicked.bind(this));
}

Inside it, get a DOM reference to add the contact button and attach a click event to it with a callback function.

在其中,获取一个DOM引用以添加联系人按钮,并使用回调函数将click事件附加到它。

5. Create an addContactBtnClicked() function.

5.创建一个addContactBtnClicked()函数。

addContactBtnClicked() {    // get the add contact form inputs 
const $addContactInputs = document.getElementsByClassName('add-contact-input'); // this object will hold the new contact information
let newContact = {}; // loop through View to get the data for the model
for (let i = 0, len = $addContactInputs.length; i < len; i++) { let key = $addContactInputs[i].getAttribute('data-key');
let value = $addContactInputs[i].value;
newContact[key] = value;
} // passing new object to the addContact method
addressBookApp.addContact(newContact); // render the contact list with the new data set
this.renderContactListModule();}

Inside it, get an array of input elements and loop through them. Create an object by setting the key from the attribute data-key of the input element and the value from the value of the input element on each iteration.

在其中,获取输入元素数组并循环遍历它们。 通过在每次迭代中设置来自输入元素的属性data-key的键和来自输入元素的值的值来创建对象。

Then, invoke addContact() by passing the object as an argument which will add it to the contactsData model array.

然后,通过将对象作为参数传递来调用addContact(),它将把它添加到contactsData模型数组中。

Then, invoke the renderContactListModule() method to re-render the View after the new data has been added.

然后,在添加新数据后,调用renderContactListModule()方法以重新渲染View。

6. Finally, call addContactModule() inside the init() method on the AddressBookView class.

6.最后,在AddressBookView类的init()方法内调用addContactModule()。

init() {
this.renderContactListModule();
this.renderContactDetailsModule(0);
this.addContactModule();
}

At this stage, you should have the add contact functionality working.

在此阶段,您应该使添加联系人功能起作用。

翻译自: https://medium.com/swlh/es6-mvc-javascript-tutorial-build-a-simple-crud-app-c402f09e69c7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值