2013-04-12 111 views
9

我創建了一個小例子,嘗試使多個模型在沒有Ember數據的情況下工作。你如何使用Ember JS中的多個模型(沒有Ember數據)?

App = Ember.Application.create(); 

App.Router.map(function() { 
    this.resource('employees', function() { 
     this.route('employee'); 
    }); 
}); 

App.Employee = Ember.Object.extend({}); 

App.Employee.reopenClass({ 
    findAll: function() { 
     return $.getJSON("http://localhost/api/employee").then(
      function (response) { 
       var employees = []; 
       response.forEach(function (child) { 
        employees.push(App.Employee.create(child)); 
       }); 
       console.log(employees.join('\n')); 
       return employees; 
      } 
     ); 
    } 
}); 

App.EmployeesController = Ember.ArrayController.extend({}); 

App.EmployeesRoute = Ember.Route.extend({ 
    model: function() { 
     return App.Employee.findAll(); 
    } 
}); 

把手:

<script type="text/x-handlebars"> 
    <p>Application template</p> 
    {{#linkTo employees}}<button>Show employees</button>{{/linkTo}} 
    {{outlet}} 
</script> 

<script type="text/x-handlebars" data-template-name="employees"> 
    <p>Employees template</p> 
    {{#each controller}} 
    <p>{{Name}}</p> 
    {{/each}} 
    {{outlet}} 
</script> 

當我瀏覽到直接localhost/#/employee URL,它工作完全正常,但是當我點擊「查看員工」按鈕,我收到以下錯誤:

Uncaught TypeError: Object #<Object> has no method 'addArrayObserver' 

我可能在某處丟失了某些東西,但我不確切地知道錯誤指向哪個對象。當我按下按鈕時,我的模型鉤子被正確調用,就像我通過手動輸入url進行導航一樣,所以我不明白在提到的兩種情況下究竟有什麼不同。

回答

10

終於得到了這個東西的工作。

我的錯誤是嘗試重新創建(讀取粘貼)Evil Trout's example做一個沒有Ember數據的Ember應用程序,並沒有足夠好地理解底層概念。

我的findAll方法正在返回一個Promise對象,儘管控制器期望一個數組,因此Uncaught TypeError。你需要做的是返回一個空的ArrayProxy,一旦收到JSON響應,它將被填充。

App.Employee.reopenClass({ 
    findAll: function() { 
     var employees = Ember.ArrayProxy.create({ content: [] }); 
     $.getJSON("http://localhost:49441/api/employee").then(
      function (response) { 
       response.forEach(function (child) { 
        employees.pushObject(App.Employee.create(child)); 
       }); 
      } 
     ); 
     return employees; 
    } 
}); 

如果你返回正確使用這種方法的數組,你不必明確指定該控制器是ArrayController

我的問題現在很愚蠢,我知道我做錯了什麼,但希望它能幫助別人入門。

相關問題