【问题标题】:Trouble while accessing to a method访问方法时出现问题
【发布时间】:2017-04-08 00:09:46
【问题描述】:

我开始使用 jquery 和 Model View ViewModel,但在使用 Event Handler Attachment 时遇到了问题:on()。 我的第一堂课是 TicTacToeModel,它在内存中操作 TicTacToe 游戏:

var TicTacToeModel = function () {
        Observable.call(this);
        this.grid = new Array(3);
        for (let i = 0; i < this.grid.length; ++i) {
            this.grid[i] = new Array(3);
        }
    };
//Some prototype function
//...

我有另一个类,TicTacToeController,它依赖于第一个类,它通过对 DOM 的操作来管理游戏的图形部分:

var TicTacToeController = function(game, selector) {
        this._element = $(selector);
        this._model = game;
        this._template = Handlebars.compile(view);
        this.addListeners();
        this.render();
    };

(游戏声明:game = new TicTacToeModel();

所以在我的第二堂课中,我有这个功能:

TicTacToeController.prototype.addListeners = function() {
    this._model.on('change', this.render, this);
    this._model.play(0,0);//works
    this._element.on('click', "td", function() {
        this._model.play(0,0);//doesn't work
    });
};

当我在图形界面中单击单元格时,我想在单元格 (0,0) 中调用 play() 函数(函数 play 更新内存中的游戏),但我无法在 .在()。但这似乎在 .on() 函数之外起作用,所以我认为 this 的使用不当会导致问题。

【问题讨论】:

    标签: javascript jquery object this


    【解决方案1】:

    你需要像这样使用bind

    改变这个:

    this._element.on('click', "td", function() {
        this._model.play(0,0);//doesn't work
    });
    

    到:

    this._element.on('click', "td", function() {
        this._model.play(0,0); //should now work
    }.bind(this));
    

    【讨论】:

    • 感谢您的回答,这工作正常,但如果我在这样的函数中添加一些 jquery :TicTacToeController.prototype.addListeners = function() { this._model.on('change', this.render, this); this._element.on('click', "td", function() { $(this).addClass("case"); $(this).html("X"); this._model.play(0,0);//doesn't work }.bind(this)); }; jquery 没有被考虑在内,你有什么想法来解决它吗?
    • 不确定您所说的“不考虑 jquery”是什么意思,但您是否尝试过 $(this._element)... 而不是 $(this)...
    • $(this._element) 不起作用,因为它改变了我的整个网格,但是如果我在 this._element.on('click', "td", function(event) {...} 中添加参数“event”,则 event.target 有效。但是为什么我不能使用 $(this) 而它代表 .on() 函数的“td”元素?
    【解决方案2】:

    您不在同一个范围内,调用 play 方法时使用的 this 变量不一样。 一个肮脏的解决方法可能是

    let _model = this._model
    this._element.on('click', "td", function() {
            _model.play(0,0);//work!
        });
    

    但正如所说的那样,这是一个肮脏的解决方法,也许其他人可以解释但基本上认为这会产生内存泄漏。也许解决方案是在同一个类中使用一个方法并将实例传递给 click 方法,有点:

    TicTacToeController.prototype.click = function() ...
    ...
    this._element.on('click', "td", this.click);
    

    认为这应该可以解决问题,但我必须承认我不是 js 专家。

    【讨论】:

    • 我也想过使用这种肮脏的解决方法,但我知道有更好的方法来解决我的问题^^。
    猜你喜欢
    • 1970-01-01
    • 2019-09-10
    • 2010-11-29
    • 1970-01-01
    • 2017-11-04
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多