如何在Ember中创建递归计算属性

时间:2013-12-31 15:06:09

标签: javascript ember.js google-chrome-extension

我正在尝试编写我的第一个ember应用程序。它是Google Chrome扩展程序,可替换新标签页。从索引路由加载应用程序时,它可以正常工作。当我重新打开子文件夹路径上的关闭选项卡(即使用此类型的文件扩展名为chrome-extension://thechromeextensionhash/index.html#/3)时,会发生错误。

错误是

  

未捕获的TypeError:无法调用方法'get'of null

path = path.concat(this.get('folder').get('path')); // inside the path computed property

这是受影响的代码:

// models/folder.js

App.Folder = DS.Model.extend({

  title: DS.attr('string'),

  level: DS.attr(),

  files: DS.hasMany('file', {
    async: true
  }),

  folders: DS.hasMany('folder', {
    async: true
  }),

  folder: DS.belongsTo('folder'),

  prefixedId: function() {
    return "folder-" + this.get('id');
  }.property('id'),

  path: function() {
    var path = [];
    if (this.get('level') !== 0) {
      path = path.concat(this.get('folder').get('path'));
    }
    path.push(this);
    return path;
  }.property('level', 'folder', 'folder.path')

});


App.Folder.FIXTURES = [
  {
    id: 1,
    title: 'Root',
    level: 0,
    bookmarks: [],
    files: [2, 3],
    folder: null
  },
  {
    id: 2,
    title: 'Folder 1',
    level: 1,
    files: [1, 2],
    folders: [],
    folder: 1
  },
  {
    id: 3,
    title: 'Folder 2',
    level: 1,
    files: [3, 4],
    folders: [4],
    folder: 1
  },
  {
    id: 4,
    title: 'Folder 4',
    level: 2,
    files: [],
    folders: [],
    folder: 3
  }
];

这是索引路线:

App.IndexRoute = Ember.Route.extend({
  redirect: function(){
    var rootFolder = this.store.find('folder', 1);
    this.transitionTo('folder', rootFolder);
  }
});

1 个答案:

答案 0 :(得分:1)

文件夹应该是异步的

folder: DS.belongsTo('folder', {
  async: true
}),

此外,文件夹可以为空,

  var parentFolder = this.get('folder');
  if (Ember.isEmpty(parentFolder){
    //do something else
  } else {
    // not empty
  }

因为文件夹是一个承诺/ null,所以你不能依赖级别来告诉你文件夹是否存在

path: function() {
  var path = [],
      parPath = this.get('folder.path');

  if (parPath) {
    path = path.concat(parPath);
  }
  path.push(this);

  return path;
}.property('folder', 'folder.path'),

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