簡體   English   中英

如何將事件從Ember.js視圖發送到其控制器

[英]How to send an event from Ember.js view to its controller

我在Ember.js應用程序中有一個自定義視圖。 看起來如下:

App.FocusView = Ember.TextField.extend({
  tagName: 'input',

  focusIn: function(){
    console.log("focus in...");
  },
  focusOut: function(){
    console.log(this.value);
    this.get('controller').send('getSalaryLookup', this.value);
  }
});

在我的模板中,我直接呈現了視圖:

{{view App.FocusView type=number value=pitcherSalary placeholder="enter pitcher salary ..."}}

我的控制器代碼已設置為接受getSalaryLookup操作:

App.OptimalController = Ember.Controller.extend({
  actions: {
    getSalaryLookup: function(pitcherSalary){
      console.log("This never hits for some reason..");
    }
  }
});

問題是我再也看不到控制器中的消息了。 我以為我正在適當地傳遞事件,但事實並非如此。 這里有明顯的錯誤嗎?

當你“動態”創建模板視圖不產生控制器,它使用的是在考慮范圍控制器(你可以做看這個{{log controller}}在同一附近{{view ...}} ,它將控制器實例發送到控制台。

但是,在這種情況下,命名並不是真正合適的,因為TextField實際上是擴展了一個組件(其內部是一個視圖,但實際上它實際上是一個組件)。 從組件發送動作的方式是,您需要在聲明動作時訂閱該動作,然后從組件中使用sendAction而不是send

App.FocusItComponent = Ember.TextField.extend({
  tagName: 'input',

  focusIn: function(){
    console.log("focus in...");
  },
  focusOut: function(){
    var value = this.get('value');
    this.sendAction('getSalaryLookup', value);
  }
});

在這里,你看我訂閱的getSalaryLookup動作名稱動作doit 當動作從組件中發出時,它將首先命中控制器,如果在那里沒有找到動作,它將命中路線,然后到達路線樹。 http://emberjs.com/guides/templates/actions/

您之所以特別訂閱,是因為您可以1.從組件中忽略不需要的操作,並且2.在同一作用域中具有多個可以執行不同操作的組件。

{{focus-it type='number' value=pitcherSalary getSalaryLookup='doit' placeholder="enter pitcher salary ..."}}

示例: http//emberjs.jsbin.com/kuxilefu/1/edit

可以在這里了解組件的命名: http : //emberjs.com/guides/components/defining-a-component/

暫無
暫無

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

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