Emberjs 1.0:如何创建模型并以另一种方式显示它们

Emberjs 1.0: How to create Models and display them in another route?

本文关键字:模型 另一种 方式 显示 创建 何创建 Emberjs      更新时间:2023-09-26

我正试图在一条路由中创建一个集合("content"),并将它们传递到另一条路由以显示它们。这里怎么了?

错误:"StartView中的内容未定义"

这是代码

http://jsfiddle.net/insnet/cmBgz/21/

App = Ember.Application.create({LOG_TRANSITIONS: true});
App.ApplicationController = Ember.Controller.extend();
App.ApplicationView = Ember.View.extend({
    templateName: 'application'
});

/* Routing */
App.Router.map(function() {
    this.route("start", {path: '/'});
    this.route("photos");
});
/* Start */
App.StartController = Ember.ArrayController.extend({
    createModels: function() {
        this.set('content', Ember.A());
        this.addObject(Ember.Object.create({id: 1, title: 'Hello'}));
        this.addObject(Ember.Object.create({id: 2, title: 'Digital'}));
        this.addObject(Ember.Object.create({id: 3, title: 'World'}));
        this.transitionToRoute('photos');   
    }
});
/* Photos */
App.PhotosView = Ember.CollectionView.extend({
    contentBinding : 'App.StartController.content',
    didInsertElement : function() {
        console.info("content in StartView", this.get('content'));
    }
});

<script type="text/x-handlebars" data-template-name="application">
  <div class="contrainer">
          <div class="hero-unit">
    <h1>My App</h1>
    {{outlet}}
    </div>
  </div>
</script>
<script type="text/x-handlebars" data-template-name="start">
    <h2>View:Start</h2>
    <button  {{action "createModels"}} class="btn btn-primary">Create models and goto '/photos'</button>
</script>
<script type="text/x-handlebars" data-template-name="photos">
    <h2>View:Photos</h2>
    {{#each controller}}
    <p>{{title}}</p>
    {{/each}}
</script>

我将您的fiddle更新为工作版本:http://jsfiddle.net/mavilein/cmBgz/22/

起初,这是小提琴中的错误/误解

1-这个绑定不起作用,因为你引用的是控制器类,而不是Ember框架创建的实例。

App.PhotosView = Ember.CollectionView.extend({
    contentBinding : 'App.StartController.content',

2-您的视图中的日志消息是错误的,不能以这种方式工作。如果要访问视图的"基础内容",请始终使用属性"context"。术语"内容"仅与控制器一起使用。

/* Photos */
App.PhotosView = Ember.View.extend({
    didInsertElement : function() {
        console.info("content in StartView", this.get('context.content'));
    }
});

这是您问题的可能解决方案:

a-这是一种可能的方式来查找startController的实例,并将其内容设置为照片路由的生成控制器的内容:

App.PhotosRoute = Ember.Route.extend({
    model : function(){
        var startController = this.controllerFor("start"); //in routes you have access to controllers with this method
        return startController.get("content");
    }
});

b-另一种可能性是手动声明路由的控制器,并使用Ember依赖注入(可能是最"余烬"的解决方案):

App.PhotosController = Ember.ArrayController.extend({
    needs : ["start"], // "I need the startController plz!" -> accessible via "controllers.start"
})
/* The corresponding each in your template would look like this */
{{#each controller.controllers.start}}