简体   繁体   English

Ember.js-如何使用Ember.Router将集合正确绑定到视图?

[英]Ember.js - How to properly bind a collection to a view using Ember.Router?

I was previously working with Ember.StateManager and now I'm doing some tests before I finally switch to Ember.Router , but I'm failing to understand how to properly bind my view data from the collection residing in my controller. 我以前使用过Ember.StateManager ,现在我进行了一些测试,最后才切换到Ember.Router ,但是我无法理解如何正确地绑定来自控制器中集合的视图数据。

I have a very simple testing structure with Ember.Router which is working fine navigation-wise , but when it comes to data binding it's not working as expected, and I confess I'm lost now. 我在Ember.Router有一个非常简单的测试结构,可以很好地进行导航 ,但是在数据绑定方面,它不能按预期工作,我承认我现在迷路了。 As for my data, I have a simple ASP.NET MVC4 Web API running a REST service which is working fine (I have tested with Fiddler and it's all good). 至于我的数据,我有一个运行REST服务的简单ASP.NET MVC4 Web API,它运行良好(我已经使用Fiddler进行了测试,这一切都很好)。 Storing in SQL with EF4.* and no problems there. 使用EF4。*存储在SQL中,没有问题。

As for the client app, in my contacts.index route, I tried binding it in the connectOutlets (should I be doing this in a different method?), but my code doesn't seem to be working correctly since my view is never bound. 对于客户端应用程序,在我的contacts.index路由中,我尝试将其绑定到connectOutlets (我应该用其他方法执行此操作吗?),但是我的代码似乎无法正常工作,因为我的视图从未绑定。

What I have tried before, in the connectOutlets method of contacts.index route: 我以前尝试过的方法,在contacts.index路由的connectOutlets方法中:

1 1个

router.get('applicationController').connectOutlet('contact');

2 2

router.get('applicationController').connectOutlet(
    'contact',
    router.get('contactController').findAll()
);

I've also tried to use the enter method with 我也尝试将enter方法与

this.setPath('view.contacts',  router.get('contactController').content);

And I have tried to bind it directly in the view like: 而且我尝试将其直接绑定在如下视图中:

App.ContactView = Ember.View.extend({
    templateName: 'contact-table'
    contactsBinding: 'App.ContactController.content'
});

Here's the current version of my code: 这是我的代码的当前版本:

var App = null;

$(function () {

    App = Ember.Application.create();

    App.ApplicationController = ...
    App.ApplicationView = ...

    App.HomeController = ...
    App.HomeView = ...

    App.NavbarController = ...
    App.NavbarView = ...

    App.ContactModel = Ember.Object.extend({
        id: null,
        firstName: null,
        lastName: null,
        email: null,
        fullName: function () {
            return '%@ %@'.fmt(this.firstName, this.lastName)
        }.property('firstName', 'lastName')
    });

    App.ContactController = Ember.ArrayController.extend({
        content: [],
        resourceUrl: '/api/contact/%@',
        isLoaded: null,

        findAll: function () {
            _self = this;
            $.ajax({
                url: this.resourceUrl.fmt(''),
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    $(data).each(function () {
                        _self.pushObject(App.ContactModel.create({
                            id: this.Id,
                            firstName: this.FirstName,
                            lastNaem: this.LastName,
                            email: this.Email
                        }));
                    });
                    alert(_self.get('content').length);
                    // this alerts 6 which is the same number of
                    // records in my database, and if I inspect
                    // the content collection in chrome, I see my data
                    // that means the problem is not the ajax call
                },
                error: function (xhr, text, error) {
                    alert(text);
                }
            });
        },
        find: function (id) {
            // GET implementation
        },
        update: function (id, contact) {
            // PUT implementation
        },
        add: function (contact) {
            // POST implementation
        },
        remove: function(id) {
            // DELETE implementation
        }
    });

    App.ContactView = Ember.View.extend({
        templateName: 'contact-table'
    });
    App.ContactListItemView = Ember.View.extend({
        templateName: 'contact-table-row'
    });

    App.Router = Ember.Router.extend({
        enableLogging: true,
        location: 'hash',

        root: Ember.Route.extend({
            // actions
            gotoHome: Ember.Route.transitionTo('home'),
            gotoContacts: Ember.Route.transitionTo('contacts.index'),

            // routes
            home: Ember.Route.extend({
                route: '/',
                connectOutlets: function (router, context) {
                    router.get('applicationController').connectOutlet('home');
                }
            }),
            contacts: Ember.Route.extend({
                route: '/contacts',
                index: Ember.Route.extend({
                    _self: this,
                    route: '/',
                    connectOutlets: function (router, context) {
                        router.get('contactController').findAll();
                        router.get('applicationController').connectOutlet('contact');
                        router.get('contactView').set('contacts', router.get('contactController').content);
                        // if I inspect the content collection here, it's empty, ALWAYS
                        // but if I access the same route, the controller will alert 
                        // the number of items in my content collection
                    }
                })
            })
        })
    });
    App.initialize();
});

Here are the relevant templates: 以下是相关模板:

<script type="text/x-handlebars" data-template-name="contact-table">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            {{#if contacts}}
                {{#each contact in contacts}}
                    {{view App.ContactListItemView contactBinding="contact"}}
                {{/each}}
            {{else}}
                <tr>
                    <td colspan="2">
                    You have no contacts <br />
                    :( 
                    <td>
                </tr>
            {{/if}}
        </tbody>
    </table>
</script>

<script type="text/x-handlebars" data-template-name="contact-table-row">
    <tr>
        <td>
            {{contact.fullName}}
        </td>
        <td>
            e-mail: {{contact.email}}
        </td>
    </tr>
</script>

As a test, I've also tried manually populat the content collection in my controller like the following, but again, it was empty when I navigated to that route: 作为测试,我还尝试了如下所示在控制器中手动填充content集合,但同样,当我导航到该路线时,它为空:

App.ContactController =  Ember.ArrayController.extend({
    content: [],
    init: function() {
        this._super();
        this.pushObject(
            App.ContactModel.create({ ... })
        );
    }
})

Right, if you manage to read until now, here's my question: How to properly bind a collection to a view using Ember.Router? 是的,如果您设法阅读到现在,这是我的问题:如何使用Ember.Router将集合正确绑定到视图?

I have seen a number of examples, as well as other questions in SO, and I haven't seen anything that works for me yet (feel free to point out other samples with binding ) 我已经看到了许多示例以及SO中的其他问题,但是我还没有发现任何对我有用的东西(可以指出其他具有约束力的示例)

Thank you 谢谢

The binding doesn't work because "the array is mutating, but the property itself is not changing". 绑定不起作用,因为“数组正在变异,但属性本身未更改”。 https://stackoverflow.com/a/10355003/603636 https://stackoverflow.com/a/10355003/603636

Using App.initialize and Ember.Router, views and controllers are now being automagically connected. 使用App.initialize和Ember.Router,现在可以自动连接视图和控制器。 There is very little reason to manually bind contacts in your view to the controller's content as you already have access to it. 由于您已经可以访问视图,因此几乎没有理由将视图中的联系人手动绑定到控制器的内容。

Change your view's template to include: 更改视图的模板以包括:

{{#if controller.isLoaded}} // set this true in your ajax success function
  {{#each contact in controller}}
    {{view App.ContactListItemView contactBinding="contact"}}
  {/each}}
{{else}}
  <tr>
    <td colspan="2">
       You have no contacts <br />
       :( 
    <td>
  </tr>
{{/if}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM