2015-05-12 38 views
0

我正在構建一個Ember應用程序,它需要在窗體輸入變爲焦點時淡出背景DIV。Ember - 如何將數據發送到組件?

我已經在我的應用程序路線上定義了操作,並在我的模型中設置了一個屬性(因爲我試圖在沒有控制器的情況下執行此操作,如Ember 2.0方式)。我正在嘗試執行操作,數據丟失。我有行動應用程序路線,但數據只是沒有回到組件。

我有冒泡到應用程序路線的行爲很好,但是當我更新屬性this.controllerFor('application').set('showBackground', true);它永遠不會讓它回到組件。

我在我的網站的每條路線上都有這種淡出的背景圖像,所以將所有操作移動到每條路線看起來像很多代碼重複。

我在做什麼錯?

// Application route.js 
var ApplicationRoute = Ember.Route.extend({ 

    model: function() { 
     return Ember.RSVP.hash({ 
      showBackground: false 
     });  
    }, 

    setupController: function(controller, models) { 
     controller.setProperties(models); 
    }, 

    action: { 
     showBackground: function(){ 
      // This runs fine 
      this.controllerFor('application').set('showBackground', true); 
     }, 

     hideBackground: function(){ 
      // This runs fine   
      this.controllerFor('application').set('showBackground', false);  
     } 
    } 

}); 

// Background component.js 
var BackgroundImage = Ember.Component.extend({ 

    // This never runs for some reason!? 
    controlImage: function(){ 
     if(this.get('showBackground')) { 
      // Open menu! 
      console.log('show image'); 
     } else { 
      // Close menu! 
      console.log('hide image'); 
     } 
    }.observes('showBackground') 

}); 

// Login template.hbs 
{{background-image showBackground=showBackground}} 

這是用路線代替「屬性」和控制器的正確方法嗎?所有「轉向Ember 2.0」的建議我都沒有提到如何取代高級屬性。

編輯 我創建了一個JSbin,但我不知道這是否是正確設置爲2.0風格(無控制器),作爲導入/導出(ES6?)的東西不能在JSbin工作。

http://emberjs.jsbin.com/wunalohona/1/edit?html,js,console,output

我不能真正得到任何的行動泡正確。

+0

是否定義'showBackground'你'Application'控制器上?另外,你正在把'showBackground'傳遞到你的把手_('{{background-image showBackground = showBackground}}')_,但是我猜這是因爲那部分工作正在將引用傳遞給'action'。您可能有一些命名衝突嘗試傳遞'showBackground'屬性_and_對'showBackground'動作的引用:'{{background-image showBackground = showBackground showBackground = showBackground}}' –

+0

您可以在emberjs.jsbin創建一個失敗的bin .com – blessenm

+0

@blessenm新增JSbin。 Thnaks看看! –

回答

3

Here is the working demo.

有您所提供的jsbin多個問題。以下是我修復的一些問題。

  1. 您需要指定路徑,App名稱空間上的組件或Ember將無法找到它。在ember-cli中使用的解析器是自定義的。

    var ApplicationRoute = Ember.Route.extend({應該是 App.ApplicationRoute = Ember.Route.extend({

    var BackgroundImage = Ember.Component.extend({應該是 App.BackgroundImageComponent = Em.Component.extend({

More about it here.

  • 您不需要在路由中指定setupController方法。默認情況下,從模型鉤子返回的模型設置爲控制器的模型屬性。

    https://github.com/emberjs/ember.js/blob/v1.11.1/packages/ember-routing/lib/system/route.js#L1543

  • ObjectController與ObjectController沿着代理行爲已被棄用。

    現在,通過在ApplicationRoute加入model. + modelPropertyName You can read more about this in the deprecation page for v1.11

  • action參考模型屬性應該是actions

  • +0

    這是非常有用的,我敢說這應該在官方文檔! –

    +0

    'model。+ modelPropertyName'效果很好,但是如果這樣的東西沒有存儲在模型中?這種類型的設置對於控制器屬性來說似乎很完美,但我永遠無法弄清楚如何將它們設置在路由上? –

    +1

    這是你可以使用setupController的時候。只需要記住調用super或將模型設置到控制器。 http://emberjs.jsbin.com/jukaco/2/edit?html,js輸出 – blessenm