在Ember.js中,每個(gè)路由都有一個(gè)關(guān)聯(lián)的模型。 {{link-to}}或transitionTo()方法將一個(gè)參數(shù)作為實(shí)現(xiàn)路由模型鉤子的模型。該模型有助于提高應(yīng)用程序的魯棒性和性能。 Ember.js使用Ember Data,它使用服務(wù)器中存儲的數(shù)據(jù)操作,并且易于使用流處理API(如socket.io和Firebase或WebSockets)。
存儲
模型
記錄
適配器
序列化器
自動緩存
存儲是應(yīng)用程序中可用的所有記錄的中央存儲庫和緩存。路由和控制器可以訪問您的應(yīng)用程序的存儲數(shù)據(jù)。自動創(chuàng)建DS.Store以在整個(gè)對象之間共享數(shù)據(jù)。
Ember.Route.extend({ model: function() { return this.store.find(); } });
模型是定義屬性和行為的數(shù)據(jù)的類。當(dāng)用戶刷新頁面時(shí),頁面的內(nèi)容應(yīng)由模型表示。
DS.Model.extend({ birthday: DS.attr('date') });
記錄是模型的實(shí)例,其包含從服務(wù)器加載的信息,并且通過其模型類型和標(biāo)識唯一標(biāo)識。
this.store.find('model_type', id)
適配器是一個(gè)對象,負(fù)責(zé)將請求的記錄轉(zhuǎn)換為對特定服務(wù)器后端的適當(dāng)調(diào)用。
序列化器負(fù)責(zé)將JSON數(shù)據(jù)轉(zhuǎn)換為記錄對象。
存儲緩存自動記錄,并且當(dāng)從服務(wù)器第二次獲取記錄時(shí),它返回相同的對象實(shí)例。這將提高應(yīng)用程序的性能。
<!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"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </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> <script type="text/x-handlebars" data-template-name="posts"> <h2>Books Name and Author: </h2> {{#each post in controller}} <p><b>{{post.book}}</b></p> <p><i>{{post.author}}<i></p> {{/each}} </script> <script type="text/javascript"> 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' }]; </script> </body> </html>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上面的代碼保存在models.htm文件中
在瀏覽器中打開此HTML文件。
讓我們通過點(diǎn)擊以下鏈接看到一些關(guān)于模型的更多詳細(xì)信息:
更多建議: