Ember.js - 如何使用Ember.Router将集合正确绑定到视图? [英] Ember.js - How to properly bind a collection to a view using Ember.Router?

查看:84
本文介绍了Ember.js - 如何使用Ember.Router将集合正确绑定到视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前在使用 Ember.StateManager ,现在我在做一些测试,我最后切换到 Ember.Router ,但是我不明白如何正确绑定我的控制器中的集合的查看数据。



我有一个非常简单的测试结构, code> Ember.Router 这是正常的导航方式,但是当涉及到数据绑定它不能按预期工作,我承认我失去了现在。对于我的数据,我有一个简单的ASP.NET MVC4 Web API运行REST服务,这是正常工作(我已经用Fiddler测试,这一切都很好)。存储在SQL中与EF4。*,没有问题。



对于客户端应用程序,在我的 contacts.index 路由,我试图在 connectOutlets 中绑定它(我应该用不同的方法做这个),但是我的代码似乎没有正常工作,因为我的观点永远不会束缚



我以前尝试过的 connectOutlets 方法 contacts.index 路线:



1

  router.get ( '的​​ApplicationController')connectOutlet( '接触')。 

2

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

我也尝试使用输入方法与

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

我已经尝试在视图中直接绑定,如:

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

以下是我的代码的最新版本:

  var App = null; 

$(function(){

App = Ember.Application.create();

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

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

App.NavbarController = ... $

$ b App.ContactModel = :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:'G ET',
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);
//这个警报6是我的数据库中相同数量的
//记录,如果我检查
// chrome中的内容集合,我看到我的数据
//这意味着问题不是ajax调用
},
错误:function(xhr,text,error){
alert(text);
}
});
},
find:function(id){
// GET implementation
},
update:function(id,contact){
// PUT实现
},
add:function(contact){
// POST implementation
},
remove:function(id){
// DELETE实现
}
});

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'),

// route
home:Ember.Route.extend({
route:'/',
connectOutlets:function(router,context){
router。 get('applicationController')connectOutlet('home');
}
}),
联系人:Ember.Route.extend({
route:'/ contacts'
index:Ember.Route.extend({
_self:this,
route:'/',
connectOutlets:function(router,context){
router。得到('contactContro lll')findAll();
router.get('applicationController')。connectOutlet('contact');
router.get('contactView')。set('contacts',router.get('contactController')。content);
//如果我在这里检查内容集合,它是空的,ALWAYS
//但如果我访问相同的路由,控制器将警告
//我的内容集合中的项目数量
}
})
})
})
});
App.initialize();
});

以下是相关模板:

 < script type =text / x-handlebarsdata-template-name =contact-table> 
< table>
< thead>
< tr>
< th> Name< / th>
< th>电子邮件< / th>
< / tr>
< / thead>
< tbody>
{{#if contacts}}
{{#each contact in contacts}}
{{view App.ContactListItemView contactBinding =contact}}
{{/ each} }
{{else}}
< tr>
< td colspan =2>
您没有联系人< br />
:(
< td>
< / tr>
{{/ if}}
< / tbody>
< / table> ;
< / script>

< script type =text / x-handlebarsdata-template-name =contact-table-row>
< ; tr>
< td>
{{contact.fullName}}
< / td>
< td>
电子邮件:{{contact .email}}
< / td>
< / tr>
< / script>

作为测试,我也尝试在我的控制器中手动填充内容集合,如下所示,但再次,它是空的当我导航到这条路线:

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

})

对,如果你直到现在读书,这是我的问题:
如何使用Ember.Router将集合正确绑定到视图?



我已经看到了一些例子,以及SO中的其他问题,以及我没有看到任何适用于我的东西(随意指出其他样本带有约束力



谢谢

解决方案

绑定不起作用,因为数组是变异的,但属性本身没有变化。 https://stackoverflow.com/a/10355003/603636



使用App.initialize和Ember.Router,视图和控制器现在正在自动连接。您已经有权访问控制器的内容,手动将视图中的联系人手动绑定到控制器的内容很少。



将视图的模板更改为包括:

  {{#如果controller.isLoaded}} //在你的ajax成功函数中设置这个true 
{{#each contact in controller }}
{{view App.ContactListItemView contactBinding =contact}}
{/ each}}
{{else}}
< tr>
< td colspan =2>
您没有联系人< br />
:(
< td>
< / tr>
{{/ if}}


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.

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. 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). Storing in SQL with EF4.* and no problems there.

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.

What I have tried before, in the connectOutlets method of contacts.index route:

1

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

2

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

I've also tried to use the enter method with

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:

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?

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)

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

Using App.initialize and Ember.Router, views and controllers are now being automagically connected. 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}}

这篇关于Ember.js - 如何使用Ember.Router将集合正确绑定到视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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