簡體   English   中英

你如何使用Ember JS中的多個模型(沒有Ember數據)?

[英]How do you work with multiple models in Ember JS (without Ember Data)?

我創建了一個小例子來嘗試使多個模型在沒有Ember Data的情況下工作。

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導航一樣,所以我不明白在提到的兩種情況下究竟有什么不同。

終於有了這個功能。

我的錯誤是嘗試重新創建(讀取復制粘貼) Evil Trout的示例 ,即在沒有Ember Data 的情況下執行Ember應用程序,並且不能很好地理解基礎概念。

我的findAll方法返回一個Promise對象,盡管控制器需要一個數組,因此是Uncaught TypeError 您需要做的是返回一個空的ArrayProxy ,一旦收到JSON響應,就會填充該ArrayProxy

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

我的問題有點愚蠢,因為我知道我做錯了什么,但希望它會幫助別人開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM