簡體   English   中英

Emberjs 1.0:如何創建模型並在另一條路線中顯示它們?

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

我試圖在一個路線中創建一個集合('內容')並將它們傳遞到另一個路線以顯示它們。 這有什么不對?

錯誤:“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>

我更新了你的小提琴到一個工作版本: http//jsfiddle.net/mavilein/cmBgz/22/

起初,這是小提琴中的錯誤/誤解

1 - 此綁定不起作用,因為您正在引用控制器類,而不是由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}}

暫無
暫無

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

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