简体   繁体   English

处理动态生成的JavaScript对象上的事件

[英]Handling events on dynamically generated JavaScript objects

I have an object I created in JavaScript. 我有一个用JavaScript创建的对象。 Let's say it looks like this: 假设它看起来像这样:

function MyObject() {
    this.secretIdea = "My Secret Idea!";
};

MyObject.prototype.load = function() {
    this.MyButton = $(document.createElement("a"));
    this.MyButton.addClass("CoolButtonClass");
    this.MyButton.click = MyButton.onButtonClick;
    someRandomHtmlObject.append(this.MyButton);
};

MyObject.prototype.onButtonClick = function(e) {
    alert(this.secretIdea);
};

As you can see, I have an object setup in JavaScript and, when it's loaded, it creates an anchor tag. 如您所见,我在JavaScript中设置了一个对象设置,并在加载对象时创建了一个定位标记。 This anchor tag as a background image in CSS (so it's not empty). 该锚标记在CSS中作为背景图片(因此它不是空的)。

Now, I understand that the 'this' statement, when the button would actually be clicked, would fall to the scope of the MyButton element rather than the object I have created. 现在,我知道当实际单击按钮时,“ this”语句将属于MyButton元素的范围,而不是我创建的对象。

I have tried using call(), try() and bind() and I cannot get this to work. 我已经尝试使用call(),try()和bind(),但我无法使用它。 I need it so that, when the button is clicked, it goes back to the object's scope and not the html element's scope. 我需要它,以便在单击按钮时,它返回到对象的作用域而不是html元素的作用域。

What am I missing here? 我在这里想念什么?

The this value inside the click event handler refers to the DOM element, not to the object instance of your constructor. click事件处理程序中的this值引用DOM元素,而不是构造函数的对象实例。

You need to persist that value, also you refer to MyButton.onButtonClick I think you want to refer the onButtonClick method declared on MyObject.prototype : 您需要保留该值,也要引用MyButton.onButtonClick我想您要引用MyObject.prototype声明的onButtonClick方法:

MyObject.prototype.load = function() {
    var instance = this;
    //..
    this.MyButton.click(function (e) { // <-- looks like you are using jQuery
      // here `this` refers to `MyButton`
      instance.onButtonClick(e);
    });
    //...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM