Table of Contents
Use data
Define model
公开您的数据
Welcome to Ember.js
{{headerName}}
下一步...模板
Home CMS Tutorial WordPress Enter Ember.js Part Three: A Deeper Dive

Enter Ember.js Part Three: A Deeper Dive

Aug 30, 2023 pm 05:13 PM
data binding Component development emberjs in depth

Enter Ember.js Part Three: A Deeper Dive

I hope you start to realize that Ember.js is a powerful but opinionated framework. We've only scratched the surface of it; there's a lot more to learn before we can build something truly useful! We will continue to use the Ember starter kit. In this part of the series, we'll review how to access and manage data in Ember.


Use data

In the previous article, we used a set of static color names defined in the controller:

App.IndexRoute = Ember.Route.extend({
 setupController: function(controller) {
   controller.set('content', ['red', 'yellow', 'blue']);
 }
});
Copy after login

This allows the controller to expose data to the index template. This is cute for demos, but in real life our data source wouldn't be a hardcoded array.

This is where models come in. A model is an object representation of data used by an application. It can be a simple array or data dynamically retrieved from a RESTful JSON API. The data itself is accessed by referencing the model's properties. So if we look at the result like this:

{
   "login": "rey",
   "id": 1,
   "age": 45,
   "gender": "male"
}
Copy after login

The properties exposed in the model are:

  • login
  • hand
  • age
  • gender

Access the data itself by referencing the model's properties.

As you can see from the code above, you can define a static storage, but most of the time you will use Ember.Object to define the model. By subclassing Ember.Object you will be able to return data (for example: via Ajax calls) and define your model. Although you can set data explicitly in the controller, it is always recommended that you create a model in order to adhere to separation of concerns and code organization best practices.

Alternatively, you can use a sister framework called Ember Data. It is an ORM-like API and persistence store, but I need to stress that it is in a state of flux at the time of writing. It has a lot of potential, but at this time it's safer to use Ember.Object. Discourse co-founder Robin Ward wrote a great blog post about using Ember without Ember data. It outlines their process and I'll break it down for you.


Define model

In the example below, I will use the unofficial Hacker News API to extract JSON-based data from a news source. This data will be stored in my model and later used by the controller to populate the template. If we look at the data returned from the API, we can understand the properties we will use:

{
  "nextId": null,
  "items": [{
          "title": "Docker, the Linux container runtime: now open-source",
          "url": "http://docker.io",
          "id": 5445387,
          "commentCount": 39,
          "points": 146,
          "postedAgo": "2 hours ago",
          "postedBy": "shykes"
      }, {
          "title": "What\u0027s Actually Wrong with Yahoo\u0027s Purchase of Summly",
          "url": "http://hackingdistributed.com/2013/03/26/summly/",
          "id": 5445159,
          "commentCount": 99,
          "points": 133,
          "postedAgo": "2 hours ago",
          "postedBy": "hoonose"
      },
  ],
  "version": "1.0",
  "cachedOnUTC": "\/Date(1364333188244)\/"
}
Copy after login

I want to use the items attribute which contains all the title and story information. If you have used a SQL database, treat each element of items as a record and attribute names (i.e.: title, url, id, etc.) are treated as field names. It's important to understand layout because these property names will be used as properties of the model object, which is a perfect interface for creating models.

Ember.Object is the main base class for all Ember objects, which we will subclass to create our model using its extend() method.

To do this, we will add the following code to js/app.js immediately after the code that defines App.IndexRoute:

App.Item = Ember.Object.extend();
Copy after login

App.Item is used as a model class for Hacker News data, but it has no methods to retrieve or manipulate that data. Therefore, we need to define these:

App.Item.reopenClass({
  all: function() {
      return $.getJSON("http://api.ihackernews.com/page?format=jsonp&callback=?").then(function(response) {
        var items = [];

        response.items.forEach( function (item) {
          items.push( App.Item.create(item) );
        });

	      return items;
      });
  }
});
Copy after login

Let’s break down this code. First, we add a new method to the App.Item class using Ember's reopenClass() method, and then pass it an object containing the method we need. For this example, we only need a method called all(): it returns all the headlines from the Hacker News homepage. Because jQuery is part of the Ember protocol, we can use its simple Ajax API. The API uses JSONP to return JSON data; so, I can use $.getJSON() to make a request to:

$.getJSON("http://api.ihackernews.com/page?format=jsonp&callback=?")
Copy after login

"callback=?" tells jQuery that this is a JSONP request and the data (once retrieved) will be passed to an anonymous callback handler defined using jQuery's Promise feature:

.then(function(response) {...});
Copy after login

I can easily inject JSON data into an Ember object.

The

response parameter contains JSON data, allowing you to loop through the records and update the local items array with an instance of App.Item. Finally, when all() executes, we return the newly populated array. Having said so much, let me summarize:

  • 通过使用 extend() 子类化 Ember.Object 来创建新模型类。
  • 使用 reopenClass() 添加模型方法。
  • 进行 Ajax 调用来检索您的数据。
  • 循环数据,创建 Item 对象并将其推入数组中。
  • 方法执行时返回数组。

如果您刷新index.html,您将看到没有任何变化。这是有道理的,因为模型刚刚被定义;我们还没有访问过它。


公开您的数据

控制器的作用类似于代理,使您可以访问模型的属性并允许模板访问它们以便动态渲染显示。除了从关联模型访问属性之外,控制器还可以存储需要持久保存的其他应用程序属性,而无需保存到服务器。

目前,我们的应用程序具有以下控制器(定义静态数据集的控制器):

App.IndexRoute = Ember.Route.extend({
  setupController: function(controller) {
    controller.set('content', ['red', 'yellow', 'blue']);
  }
});
Copy after login

我们可以使用 model 方法(又名模型钩子)直接将我们的模型与 App.IndexRoute 关联起来:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return App.Item.all();
  }
});
Copy after login

请记住,如果您自己没有显式定义控制器,那么 Ember 会定义您的控制器,这就是本例中发生的情况。

在幕后,Ember 创建 IndexController 作为 Ember.ArrayController 的实例,并使用 model 方法中指定的模型。

现在我们只需要更新索引模板即可访问新属性。打开index.html,我们可以看到以下Handlebars模板代码:

{{#each item in model}}
    <li>{{item}}</li>
{{/each}}
Copy after login

通过一个小更改(添加 title 属性),我们可以立即看到从 Hacker News API 返回的标题:

{{item.title}}

如果您现在刷新浏览器,您应该会看到类似以下内容的内容:

<h3 id="Welcome-to-Ember-js">Welcome to Ember.js</h3>
<ul><li>Persona is distributed. Today.</li>
<li>21 graphs that show America's health-care prices are ludicrous</li>
<li>10 000 concurrent real-time connections to Django</li>
<li>Docker, the Linux container runtime: now open-source</li>
<li>Let's Say FeedBurner Shuts Down…</li></ul>
Copy after login

如果您想显示更多信息,只需添加更多属性:

{{item.title}} - {{item.postedAgo}} by {{item.postedBy}}
Copy after login

刷新即可查看您所做的更新。这就是 Handlebars 的魅力所在;它使得向用户界面添加新数据元素变得微不足道。

正如我之前提到的,控制器还可以用于定义需要在应用程序的整个生命周期中保留的静态属性。例如,我可能想保留某些静态内容,如下所示:

App.IndexController = Ember.ObjectController.extend({
  headerName: 'Welcome to the Hacker News App',
  appVersion:  2.1
});
Copy after login

在这里,我将 Ember.ObjectController 子类化,为我的 index 路由和模板创建一个新的控制器。我现在可以转到 index.html 并更新我的模板以替换以下内容:

<h2 id="Welcome-to-Ember-js">Welcome to Ember.js</h2>
Copy after login

与:

<h2 id="headerName">{{headerName}}</h2>
Copy after login

模型是应用程序使用的数据的对象表示。

Handlebars 将采用我的控制器中的指定属性,并用其同名值动态替换 {{headerName}} 占位符。强调两件事很重要:

  • 通过遵守 Ember 的命名约定,我无需进行任何接线即可将控制器与索引模板一起使用。
  • 即使我显式创建了 IndexController,Ember 也足够聪明,不会覆盖通过路由关联的现有模型。

这是非常强大且灵活的东西!


下一步...模板

在 Ember 中处理数据并不困难。实际上,最困难的部分是使用网络上大量的各种 API。

事实上,我可以轻松地将 JSON 数据输入到 Ember 对象中,这使得管理变得更加容易 — 尽管我从来都不是客户端大型数据集的忠实粉丝,尤其是当表示为对象时.

这是我必须做更多测试的事情,我希望 Ember Data 能让这一切变得微不足道。

话虽如此,我在本文中简要介绍了模板。它们非常重要……以至于我想在自己的文章中讨论这个主题。因此,在下一篇文章中,我们将介绍如何利用 Handelbars 构建用户界面,并深入了解模板框架提供的各种指令。

The above is the detailed content of Enter Ember.js Part Three: A Deeper Dive. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement data binding function in SwiftUI using MySQL How to implement data binding function in SwiftUI using MySQL Jul 30, 2023 pm 12:13 PM

How to use MySQL to implement data binding function in SwiftUI. In SwiftUI development, data binding can realize automatic updating of interface and data, improving user experience. As a popular relational database management system, MySQL can store and manage large amounts of data. This article will introduce how to use MySQL to implement data binding function in SwiftUI. We will make use of Swift's third-party library MySQLConnector, which provides connections and queries to MySQL data.

Detailed explanation of data binding functions in Vue documentation Detailed explanation of data binding functions in Vue documentation Jun 20, 2023 pm 10:15 PM

Vue is an open source JavaScript framework mainly used for building user interfaces. The core of Vue is data binding, which provides a convenient and efficient way to achieve two-way binding between data and views. Vue's data binding mechanism is handled through some special functions. These functions can help us automatically bind the data in the template to the corresponding properties in the JavaScript object, so that when the properties in the JavaScript object are modified, the data in the template will also automatically

How to use the v-once directive to implement one-time rendering of data binding in Vue How to use the v-once directive to implement one-time rendering of data binding in Vue Jun 11, 2023 pm 01:56 PM

Vue is a popular front-end JavaScript framework that provides many instructions to simplify the data binding process. One of the very useful instructions is v-once. In this article, we will delve into the use of the v-once directive and how to implement data-bound one-time rendering in Vue. What is the v-once instruction? v-once is a directive in Vue. Its function is to cache the rendering results of elements or components so that their rendering process can be skipped in subsequent updates.

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Aug 19, 2023 pm 08:46 PM

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Introduction: Two-way data binding is a very common and powerful feature when developing with Vue. However, sometimes we may encounter a problem, that is, when we try to use v-model for two-way data binding, we encounter an error. This article describes the cause and solution of this problem, and provides a code example to demonstrate how to solve the problem. Problem Description: When we try to use v-model in Vue

Detailed explanation of v-model function in Vue3: application of two-way data binding Detailed explanation of v-model function in Vue3: application of two-way data binding Jun 18, 2023 am 10:25 AM

With the continuous development of front-end technology, Vue, as a popular front-end framework, is also constantly updated and iterated. The latest version, Vue3, introduces many new features, making it more convenient and flexible to use. Among them, the v-model function is one of the new features worth mentioning in Vue3. It can achieve two-way data binding, that is to say, when using the v-model function, it can not only easily realize communication between parent and child components, but also automatically bind the data input by the user to the data in the component.

How to use Vue for form validation and data binding How to use Vue for form validation and data binding Aug 02, 2023 am 10:54 AM

How to use Vue for form validation and data binding Introduction: With the continuous development of front-end development, form validation of user input has become an important link. As a popular front-end framework, Vue.js provides a series of functions to simplify the process of form validation and data binding. This article will introduce how to use Vue for form validation and data binding, and give corresponding code examples. 1. Basic data binding: In Vue, we can use the v-model directive to achieve two-way binding of data. Place the input element

Vue development experience summary: improve the collaboration efficiency of the development team Vue development experience summary: improve the collaboration efficiency of the development team Nov 02, 2023 pm 01:27 PM

Vue.js is a popular front-end development framework. It is easy to learn, flexible, scalable and efficient, so it is widely used in development teams. This article will summarize Vue development experience from several aspects to improve the collaboration efficiency of the development team. 1. Component-based development thinking The core idea of ​​Vue.js is component-based development, which splits complex applications into multiple independent components to increase reusability and maintainability. During the development process, team members should fully understand and apply componentization ideas, rationally design and split components, and reduce components

Vue Development Notes: Avoid Common Mistakes and Pitfalls Vue Development Notes: Avoid Common Mistakes and Pitfalls Nov 23, 2023 am 10:37 AM

Vue Development Notes: Avoid Common Mistakes and Pitfalls Introduction: Vue.js is a popular JavaScript framework that is widely used to build modern interactive front-end applications. Although Vue.js provides a simple, flexible and efficient development method, you may still encounter some common errors and pitfalls during the development process. This article will introduce some common Vue development considerations to help developers avoid these mistakes and traps and improve development efficiency and code quality. Note 1: Reasonable use of v-if and

See all articles