从组件内部调用 Ember 组件操作



我正在创建一个组件来包装 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:change,或者我是否可以在on("change")事件中设置selectedValue属性本身

"

this"不是"//发送到更改"行中的组件 - 此时我如何/在哪里获得对组件本身的引用?

基本上我试图实现的是将传递给 select2 的"change"事件的数据放入我的 selectedValue 属性中

谢谢

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

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

this上下文不会引用$.each中的FixedSelectComponent上下文,并且还使用将调用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'只是组件上的另一个属性。

试试这个:

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);

最新更新