没有 Ember 数据的 Ember [英] Ember without Ember Data

查看:15
本文介绍了没有 Ember 数据的 Ember的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ember 数据仍然不是 1.0 版本,因此我决定使用 Ember 而不使用数据模型.

我有自己的模型,这些模型是由路由模型函数创建的.

然而,在前端对象和后端对象之间维护状态是一场噩梦.特别是当一条路线使用另一条路线模型时.

  • 如何实现,我应该编写自己的商店和模型查找方法吗?
  • 我是否应该使用 Ember Data(即使它不是 1.0 版?)也许是 Ember Data 1.0 的预计到达时间?
  • 每次更改模型时编写代码来更新前端的模型?
  • 另一种方法?

我正在做的是最佳实践还是应该以不同的方式做?我的直觉是,如果不使用 Ember Data,我应该编写自己的商店.我很想得到你们中的一些人的反馈.

模型示例:

App.Person = Ember.Object.extend(App.Serializable,Em.Copyable,{user_email : null//用于路由动态段和更改电子邮件时作为旧电子邮件,first_name: 空,姓氏:空,全名:函数(){返回 this.first_name + ' ' + this.last_name;}.property('first_name','last_name').cacheable()};App.Person.reopenClass({创建记录:函数(数据){返回 App.Person.create({user_email : data.email, first_name: data.first_name, last_name : data.last_name}});

我如何加载类模型的示例:

App.UsersRoute = App.AuthenticatedRoute.extend( {模型:函数(){返回新 Ember.RSVP.Promise(function(resolve, reject) {$.getJSON('/users').then(function(usersData) {var userObjects = [];usersData.forEach(函数(数据){userObjects.pushObject(App.Person.createRecord(data));});解决(用户对象);},函数(错误){拒绝(错误);});})},

子路由使用模型:

App.UsersAvailableRoute = App.AuthenticatedRoute.extend( {模型:函数(){返回 {allUsers : Ember.ArrayController.create({内容:this.modelFor('users').filter(函数(用户){返回 user.availablity === 100}),

我如何在控制器中更新模型的示例:

App.UsersAvailableController = Ember.ArrayController.extend({需求:['用户'],applyPersonAssign : 函数(人,需要,项目){need.set('已分配',person);var updateObject = Ember.copy(project,true);if (Ember.isEmpty(need.get('inProject'))) {updateObject.projectNeeds.pushObject(need);}返回 $.ajax({url: '/projects/' + updateObject.get('codename'),"类型": "放置","数据类型": "json",数据:updateObject.serialize()})

解决方案

您不一定需要重新创建 Ember 数据存储.Ember 与 POJO 配合得很好,您也可以将 POJO 包装在 Ember 对象中,以便为您提供一些有趣的内置功能.<​​/p>

也就是说,创建一个缓存结果的自定义适配器可能很方便.

这是我创建支持缓存的适配器的示例.你可以慢慢地建立你需要的所有基本东西的概念.

App.FooAdapter = Ember.Object.extend({缓存:{},查找:函数(id){var self = this,记录;if(record = this.cache[id]){返回 Ember.RSVP.cast(record);}别的{返回新 Ember.RSVP.Promise(function(resolve){解析($.getJSON('http://www.foolandia.com/foooo/' + id));}).then(函数(结果){record = self.cache[id] = App.Foo.create(result);退货记录;});}}});

在下面的示例中,我使用容器在我的所有路由/控制器上注册适配器,因此我可以轻松轻松地访问它.

http://emberjs.jsbin.com/OxIDiVU/742/edit

如果你总是希望它成为一个承诺:

http://emberjs.jsbin.com/OxIDiVU/740/edit

可重用性

上面的例子可能看起来你必须做大量的工作,但不要忘记,Ember 是超级可重用的,利用它的魔力.

App.MyRestAdapter = Em.Object.extend({类型:未定义,查找:函数(id){$.getJSON('http://www.foolandia.com/' + this.get('type') + '/' + id}});App.FooAdapter = App.MyRestAdapter.extend({类型:'foo'//这将创建对:http://www.foolandia.com/foo/1 的调用});App.BarAdapter = App.MyRestAdapter.extend({类型:'bar'//这将创建对:http://www.foolandia.com/bar/1 的调用});

这是什么是 Ember Data/Ember Model 的基本思想.他们试图创建大量默认值并内置酷炫功能,但有时这太过分了,尤其是如果您只是在消耗数据而不是进行 CRUD.

示例:http://emberjs.jsbin.com/OxIDiVU/744/edit

你也可以阅读这个(说同样的话):

如何为 ember 创建自定义适配器.js?

Ember data is still not at version 1.0 and thus I decided to use Ember without Data models.

I have my own models, and those are created by the route model function.

However maintaining state between the frontend objects and the backend objects is a nightmare. Especially when one route uses another routes models.

  • How can this be achieved, should I write my own store and model find method?
  • Should I use Ember Data (even though it's not at version 1.0 ?) perhaps an ETA on Ember Data 1.0 ?
  • write code to update the models on the frontend each time I change a model?
  • Another method?

Is what I'm doing best practices or should I be doing it differently? My gut feeling is that without using Ember Data I should write my own store. I'd love to get feedback from some of you guys.

Example of a model:

App.Person = Ember.Object.extend(App.Serializable,Em.Copyable,{
  user_email : null //used in routing dynamic segements and as old email when making changes to email
  ,first_name: null
  , last_name: null
  , fullname : function () {
    return this.first_name + ' ' + this.last_name;
  }.property('first_name','last_name').cacheable()
};

App.Person.reopenClass({
  createRecord: function(data) {
    return App.Person.create({
      user_email : data.email
      , first_name: data.first_name
      , last_name : data.last_name
}});

Example of how I load the class models:

App.UsersRoute = App.AuthenticatedRoute.extend( {
  model : function () {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      $.getJSON('/users').then(function(usersData) {
        var userObjects = [];
          usersData.forEach(function (data) {
            userObjects.pushObject(App.Person.createRecord(data));
          });
        resolve( userObjects);
        },function(error) {
          reject(error);
      });
    })
  },

Subroutes use the model:

App.UsersAvailableRoute = App.AuthenticatedRoute.extend( {
     model : function () {
        return {
          allUsers :  Ember.ArrayController.create({
            content : this.modelFor('users').filter( function (user) {
                      return user.availablity === 100
                      }),

Example of how I update the model in a controller:

App.UsersAvailableController = Ember.ArrayController.extend({
needs : ['users']
    ,applyPersonAssign : function (person,need,project) {
          need.set('allocated',person);
          var updateObject = Ember.copy(project,true);
          if (Ember.isEmpty(need.get('inProject'))) {
            updateObject.projectNeeds.pushObject(need);
          }

          return $.ajax({
            url: '/projects/' + updateObject.get('codename'),
            "type": "PUT",
            "dataType": "json",
            data: updateObject.serialize()
          })

解决方案

You don't necessarily need to recreate the Ember Data store. Ember works just fine with POJOs, you can also wrap your POJOs in an Ember Object to give you some fun built in features.

That being said creating a custom adapter which caches results could be convenient.

Here's an example where I create an adapter that supports caching. You can slowly build on the concept for all of the basic things you need.

App.FooAdapter = Ember.Object.extend({
  cache:{},
  find: function(id){
    var self = this,
        record;
    if(record = this.cache[id]){
      return Ember.RSVP.cast(record);
    }
    else
    {
      return new Ember.RSVP.Promise(function(resolve){
        resolve($.getJSON('http://www.foolandia.com/foooo/' + id));
      }).then(function(result){
        record = self.cache[id] = App.Foo.create(result);
        return record;
      });
    }
  }
});

In the examples below, I use the container to register the adapter on all of my routes/controllers so I had lazy easy access to it.

http://emberjs.jsbin.com/OxIDiVU/742/edit

If you always want it to be a promise:

http://emberjs.jsbin.com/OxIDiVU/740/edit

Reusability

The example above may make it look like you'd have to do a ton of work, but don't forget, Ember is super reusable, take advantage of the magic.

App.MyRestAdapter = Em.Object.extend({
  type: undefined,
  find: function(id){
    $.getJSON('http://www.foolandia.com/' + this.get('type') + '/' + id
  }
});

App.FooAdapter = App.MyRestAdapter.extend({
  type: 'foo' // this would create calls to: http://www.foolandia.com/foo/1
});

App.BarAdapter = App.MyRestAdapter.extend({
  type: 'bar' // this would create calls to: http://www.foolandia.com/bar/1
});

This is the basic idea of what Ember Data/Ember Model is. They've tried to create a ton of defaults and built in coolness, but sometimes it's overkill, especially if you are just consuming data and not doing CRUD.

Example: http://emberjs.jsbin.com/OxIDiVU/744/edit

Also you can read this (says the same stuff):

How do you create a custom adapter for ember.js?

这篇关于没有 Ember 数据的 Ember的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆