【问题标题】:Class as an Event Observer作为事件观察者类
【发布时间】:2011-01-23 20:12:36
【问题描述】:

我想做这样的事情......

var Color = Class.create({
    initialize: function() {
        this._color = "white";
        this.observe("evt: colorChanged", this.colorChanged.bind(this));
    },
    changeColor: function(color) {
        this._color = color;
        this.fire("evt: colorChanged");
    },
    colorChanged: function(event) {
        alert("You change my color!");
    }
});
var a = new Color().changeColor("blue");

为什么永远不会调度 colorChange 自定义事件,而我需要使用像 document.observe 这样的 DOM 元素而不是 this

在我的代码中,我想知道哪个类使用event.target 调度事件,如果我必须使用document 或其他一些DOM 元素,我就无法知道。 :(

我一直在使用 Actionscript 3,这就是我学会在类中处理自定义事件的方法。 Javascript 呢?

【问题讨论】:

    标签: javascript oop dom prototypejs custom-events


    【解决方案1】:

    这应该可行:

    var Color = Class.create({
        initialize: function() {
            this._color = "white";
            Event.observe(document, "evt: colorChanged", this.colorChanged.bind(this));
        },
        changeColor: function(color) {
            this._color = color;
            Event.fire(document, "evt: colorChanged", this, false);
        },
        colorChanged: function(event) {
            alert("You change my color!");
        }
    });
    var a = new Color().changeColor("blue");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多