Emberjs 1.0:如何创建模型并在另一条路线中显示它们?

时间:2013-02-19 23:08:56

标签: javascript ember.js

我试图在一个路线中创建一个集合('内容')并将它们传递到另一个路线以显示它们。这有什么不对?

  

错误:“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>

1 个答案:

答案 0 :(得分:3)

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

首先,这是小提琴中的错误/误解

1 - 此Binding不起作用,因为您引用的是控制器类,而不是Ember框架创建的实例。

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

2 - View中的日志消息错误,无法正常工作。如果要访问视图的“基础事物”,请始终使用属性“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 Dependency Injection(可能是最“令人讨厌的”解决方案):

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}}