无法在组件上下文中执行函数

时间:2014-08-12 05:30:50

标签: javascript ember.js

我需要执行app控制器中的bubbleData函数

以下方式无效。

this.get("data").call();
TypeError: undefined is not a function
this.get("data")();
TypeError: undefined is not a function
this.get("data")()
TypeError: undefined is not a function

控制台输出:在组件绘制功能中键入this.get(' data')

function (){
    var self = this;    
    debugger;
    return {
      name: 'tools',
      children: this.get("data").map(function(t){
        return{
          name: t.name,
          size: 300
        }
      })
    };

  } 

视图

{{bubble-chart width=560 height=350 data=bubbleData}}      

控制器

App.ApplicationController = Ember.ArrayController.extend({
  bubbleData: function(){
    var self = this;    
    debugger;
    return {
      name: 'tools',
      children: this.get("data").map(function(t){
        return{
          name: t.name,
          size: 300
        }
      })
    };
  },....

组件

App.BubbleChartComponent = Em.Component.extend({
  draw: function(){
    debugger;
  }.observes('data').on('didInsertElement')
}

1 个答案:

答案 0 :(得分:0)

该组件可以使用sendAction函数(http://emberjs.com/guides/components/sending-actions-from-components-to-your-application/)发送操作。

所以正确的方法是 hbs

data="bubbleData" 

js 的组件

this.sendAction("data");

示例

http://emberjs.jsbin.com/luwixanemunu/1/edit

但是,如果需要传递函数本身,则必须注意调用该函数的上下文。这就是this.get("data")();不起作用的原因。在示例test2中演示了调用它的正确方法,

var theController = this.get("parentView.controller");
      this.get("data2").apply(theController);

示例代码

<强> HBS

<script type="text/x-handlebars">
    <h2>Welcome to Ember.js</h2>


    {{bubble-chart width=560 height=350 data="bubbleData2" data2=bubbleData test=testProp}}   


  </script>

  <script type="text/x-handlebars" id="components/bubble-chart">
  the bubble component <br/>
  {{test}}
  <br/>
  <button {{action "test1"}}>test1</button>
  <button {{action "test2"}}>test2</button>
  </script>

<强> JS

App.ApplicationController = Ember.ArrayController.extend({
  testProp:"test",
  bubbleData: function(){
    var self = this;    
    debugger;
    return {
      name: 'tools',
      children: this.get("data").map(function(t){
        return{
          name: t.name,
          size: 300
        };
      })
    };
  },
  actions:{
    bubbleData2:function(){alert("bubbleData in actions");}
  }
});



App.BubbleChartComponent = Em.Component.extend({
  draw: function(){
//     debugger;
  }.observes('data').on('didInsertElement'),
  actions:{
    test1:function(){
      this.sendAction("data");
    },
    test2:function(){
      var theController = this.get("parentView.controller");
      this.get("data2").apply(theController);
    }
  }

});