Home > Article > CMS Tutorial > 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.
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']); } });
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" }
The properties exposed in the model are:
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.
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)\/" }
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 itsextend()
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();
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; }); } });
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=?")
"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) {...});
TheI can easily inject JSON data into an Ember object.
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()
添加模型方法。Item
对象并将其推入数组中。如果您刷新index.html,您将看到没有任何变化。这是有道理的,因为模型刚刚被定义;我们还没有访问过它。
控制器的作用类似于代理,使您可以访问模型的属性并允许模板访问它们以便动态渲染显示。除了从关联模型访问属性之外,控制器还可以存储需要持久保存的其他应用程序属性,而无需保存到服务器。
目前,我们的应用程序具有以下控制器(定义静态数据集的控制器):
App.IndexRoute = Ember.Route.extend({ setupController: function(controller) { controller.set('content', ['red', 'yellow', 'blue']); } });
我们可以使用 model
方法(又名模型钩子)直接将我们的模型与 App.IndexRoute
关联起来:
App.IndexRoute = Ember.Route.extend({ model: function() { return App.Item.all(); } });
请记住,如果您自己没有显式定义控制器,那么 Ember 会定义您的控制器,这就是本例中发生的情况。
在幕后,Ember 创建
IndexController
作为Ember.ArrayController
的实例,并使用model
方法中指定的模型。
现在我们只需要更新索引模板即可访问新属性。打开index.html,我们可以看到以下Handlebars模板代码:
{{#each item in model}} <li>{{item}}</li> {{/each}}
通过一个小更改(添加 title
属性),我们可以立即看到从 Hacker News API 返回的标题:
{{item.title}}
如果您现在刷新浏览器,您应该会看到类似以下内容的内容:
<h3>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>
如果您想显示更多信息,只需添加更多属性:
{{item.title}} - {{item.postedAgo}} by {{item.postedBy}}
刷新即可查看您所做的更新。这就是 Handlebars 的魅力所在;它使得向用户界面添加新数据元素变得微不足道。
正如我之前提到的,控制器还可以用于定义需要在应用程序的整个生命周期中保留的静态属性。例如,我可能想保留某些静态内容,如下所示:
App.IndexController = Ember.ObjectController.extend({ headerName: 'Welcome to the Hacker News App', appVersion: 2.1 });
在这里,我将 Ember.ObjectController
子类化,为我的 index 路由和模板创建一个新的控制器。我现在可以转到 index.html 并更新我的模板以替换以下内容:
<h2>Welcome to Ember.js</h2>
与:
<h2>{{headerName}}</h2>
模型是应用程序使用的数据的对象表示。
Handlebars 将采用我的控制器中的指定属性,并用其同名值动态替换 {{headerName}}
占位符。强调两件事很重要:
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!