【问题标题】:How to reference a variable of the component in a function not called in angular2/4?如何在 angular2/4 中未调用的函数中引用组件的变量?
【发布时间】:2018-04-03 09:05:05
【问题描述】:

我在我的组件中使用ztree,有一个名为addHoverDom(treeId, treeNode) 的函数,它在组件中定义,但它不像angular 通常那样被调用。下面是函数:

 addHoverDom(treeId, treeNode) {
    let aObj = $("#" + treeNode.tId + "_a");
    let addBtnId = "diy_add_" + treeNode.tId;
    let ztree = $.fn.zTree.getZTreeObj(treeId);
    if ($("#" + addBtnId).length == 0) {
      $("#" + addBtnId).bind("click", function() {
        //reference a variable of the component here
      });
    }
}

它是这样称呼的:

setting: Object = {
  callback: {
    onClick: this.zTreeOnClick
  },
  view: {
    addHoverDom: this.addHoverDom,
    removeHoverDom: this.removeHoverDom
  }
};

现在我想在函数中获取组件的变量,我尝试了组件name.prototype 并将其重命名为那个,但都不起作用,谁能帮忙?非常感谢。

【问题讨论】:

  • 函数addHoverDom是否在您要引用的组件中定义?
  • 在组件中,是ztree的一个功能,可以自定义。
  • 是的,它在组件中。

标签: angular variables ztree


【解决方案1】:

假设函数addHoverDom定义在你要引用的组件中,你可以使用箭头函数保留上下文,直接在函数addHoverDom中使用this引用组件的字段,请参考以下示例:

addHoverDom(treeId, treeNode) {
  ...
  if ($("#" + addBtnId).length == 0) {
    $("#" + addBtnId).bind("click", () => {       // use arrow function to keep context
      //reference a variable of the component here
      // example code
      this.variable_name = 'test';
      const test = this.variable_name;      
    });
  }
}

此外,您可能需要保留addHoverDom 回调的上下文

setting: Object = {
  callback: {
    onClick: this.zTreeOnClick
  },
  view: {
    addHoverDom: this.addHoverDom.bind(this),     // bind this to keep the context
    removeHoverDom: this.removeHoverDom
  }
};

【讨论】:

  • 就是这样,但是绑定这个是必须的,非常感谢。
  • @HalShaw 欢迎您!也感谢您的反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 2017-06-25
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多