EmberJS模型

EmberJS 模型

模型在Ember.js中,每个路由都有一个关联的模型。 {{link-to}}或transitionTo()方法将一个参数作为实现路由模型钩子的模型。该模型有助于提高应用程序的鲁棒性和性能。 Ember.js使用Ember Data,它使用服务器中存储的数据操作,并且易于使用流处理API(如socket.io和Firebase或WebSockets)。核心概念存储模型记录适配器序列化器自动缓存存储存储是应用程序中可用的所有记录的中央存储库和缓存。路由和控制器可以访问您的应用程序的存储数据。自动创建DS.Store以在整个对象之间共享数据。Ember.Route.extend({

model: function() {

return this.store.find();

}

});

模型模型是定义属性和行为的数据的类。当用户刷新页面时,页面的内容应由模型表示。DS.Model.extend({

birthday: DS.attr('date')

});记录记录是模型的实例,其包含从服务器加载的信息,并且通过其模型类型和标识唯一标识。this.store.find('model_type', id)适配器适配器是一个对象,负责将请求的记录转换为对特定服务器后端的适当调用。序列化器序列化器负责将JSON数据转换为记录对象。自动缓存存储缓存自动记录,并且当从服务器第二次获取记录时,它返回相同的对象实例。这将提高应用程序的性能。例子<!DOCTYPE html>

<html>

<head>

<title>Emberjs Models using Core Concepts</title>

<!-- CDN's-->

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"&gt;&lt;/script&gt;

<script src="https://code.jquery.com/jquery-2.1.3.min.js"&gt;&lt;/script&gt;

<script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"&gt;&lt;/script&gt;

<script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"&gt;&lt;/script&gt;

<script src="https://builds.emberjs.com/release/ember.debug.js"&gt;&lt;/script&gt;

<script src="https://builds.emberjs.com/beta/ember-data.js"&gt;&lt;/script&gt;

</head>

<body>

<script type="text/x-handlebars" data-template-name="index">

<h2>Models using core concepts: </h2>

<p>{{#link-to 'posts'}}Click for books Detail{{/link-to}}</p>

</script>

  &lt;script type="text/x-handlebars" data-template-name="posts"&gt;

&lt;h2&gt;Books Name and Author: &lt;/h2&gt;

{{#each post in controller}}

&lt;p&gt;&lt;b&gt;{{post.book}}&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;&lt;i&gt;{{post.author}}&lt;i&gt;&lt;/p&gt;

{{/each}}

&lt;/script&gt;

&lt;script type="text/javascript"&gt;

App = Ember.Application.create();

//The store cache of all records available in an application

App.Store = DS.Store.extend({

//adapter translating requested records into the appropriate calls

adapter: 'DS.FixtureAdapter'

});

App.ApplicationAdapter = DS.FixtureAdapter.extend(//extending Adapter);

App.Router.map(function() {

//posts route

this.resource('posts');

});

App.PostsRoute = Ember.Route.extend({

model: function() {

return this.store.find('post');

}

});

App.Post = DS.Model.extend({

//data Model

//setting book and author attr as string

book: DS.attr('string'),

author: DS.attr('string')

});

//attach fixtures(sample data) to the model's class

App.Post.FIXTURES = [{

id: 1,

book: 'Java',

author: 'Balaguruswamy'},{

id: 2,

book: 'C++',

author: 'Herbert Schildt'},{

id: 3,

book: 'jQuery',

author: 'Ryan Benedetti'

}];

&lt;/script&gt;

</body>

</html>输出让我们执行以下步骤,看看上面的代码如何工作: 将上面的代码保存在models.htm文件中在浏览器中打开此HTML文件。让我们通过点击以下链接看到一些关于模型的更多详细信息: 定义模型 创建和删除记录 将记录放入存储 持久记录 查找记录 使用记录 使用夹具 Rest适配器 连接到HTTP服务器 处理元数据 自定义适配器