簡體   English   中英

從組件內調用ember組件操作

[英]call an ember component action from within the component

我正在創建一個組件來包裝select2選擇框。 代碼如下:

App.FixedSelectComponent = Ember.Component.extend({
  actions: {
    change: function(value) {
      this.set('selectedValue',value);
    }
  },

didInsertElement : function(){
  this.$("#select1").select2().on("change", function(e) {
      if ($.isArray(e.val)) {
          $.each(e.val, function(index,value) {
              console.log("multiple:",value.split('>')[2].split('<')[0]);
             // send to change
          });             
      } else {
          console.log("single:",e.val.split('>')[2].split('<')[0]);  
          // send to change
      }
    });
  },

  willDestroyElement : function() {
    this.$("#select1").select2('destroy');
},

});

但是,我所堅持的是如何將我在on(“change”)事件中獲得的數據發送到action:更改我已定義的,或者我是否可以在on中設置selectedValue屬性(“改變”)事件

“this”不是“// send to change”行的組件 - 此時我如何/在何處獲得對組件本身的引用?

基本上我想要實現的是將傳遞給select2的“change”事件的數據放入我的selectedValue屬性中

謝謝

您可以使用Component.send('actionName')

我在Ember的文檔中找到了它。

this上下文不會引用$.each FixedSelectComponent上下文,也會使用send方法調用FixedSelectComponent更改方法。

參考: http//emberjs.com/api/classes/Ember.Component.html#method_send

didInsertElement : function(){
  var _this = this;
  this.$("#select1").select2().on("change", function(e) {
      if ($.isArray(e.val)) {
          $.each(e.val, function(index,value) {
              console.log("multiple:",value.split('>')[2].split('<')[0]);
             _this.send('change',value.split('>')[2].split('<')[0]); // send to change
          });             
      } else {
          console.log("single:",e.val.split('>')[2].split('<')[0]);  
          _this.send('change',e.val.split('>')[2].split('<')[0]); // send to change
      }
    });
  }
this.get('actions').change.call(this, value);

檢查http://emberjs.com/api/classes/Ember.Component.html#property_actions - 'actions'只是Component上的另一個屬性。

試試這個:

App.FixedSelectComponent = Ember.Component.extend({
  change: function(value) {
    this.set('selectedValue',value);
  }

  didInsertElement : function(){
    var self = this;
    this.$("#select1").select2().on("change", function(e) {
      if ($.isArray(e.val)) {
         $.each(e.val, function(index,value) {
             console.log("multiple:",value.split('>')[2].split('<')[0]);
             // send to change
             self.change(value); // substitute value by whatever you want to pass
         });             
      } else {
         console.log("single:",e.val.split('>')[2].split('<')[0]);  
         // send to change
         self.change(value); // substitute value by whatever you want to pass
      }
    });
  },

  willDestroyElement : function() {
    this.$("#select1").select2('destroy');
  },
});
this._actions['change'].apply(this, value);

暫無
暫無

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

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