gpt4 book ai didi

javascript - 我如何在winjs中的转发器元素中绑定(bind)点击事件?

转载 作者:可可西里 更新时间:2023-11-01 10:06:05 24 4
gpt4 key购买 nike

我可以通过这种方式创建转发器:

    <div class="gameField" id="gameField" data-win-control="WinJS.UI.Repeater" data-win-options="{ data: GameField.cells}">
<div class="gameCell">
<img data-win-bind="src: symbol GameField.cellSymbolToImg" width="100" height="100" />
</div>
</div>

和js

    var Cell = WinJS.Class.define(function(number) {
this.number = number;
this.symbol = "";
});

var getCellsList = function () {
var cells = [];
for (var i = 1; i < 10; i++) {
var cell = new Cell(i);

cells.push(cell);
}
return cells;
};

var cellsList = new WinJS.Binding.List(getCellsList());
WinJS.Namespace.define("GameField", {
cells: cellsList,
cellSymbolToImg: WinJS.Binding.converter(function (symbol) {
return symbol == "" ? "" : "symbol_" + symbol + ".png";
})
});

但是我如何才能将点击事件绑定(bind)到某个函数,以便我可以从该函数中访问底层单元格对象?

最佳答案

使用 function.bind 方法很简单,您甚至可以直接在 Cell 类中使用处理程序。

var Cell = WinJS.Class.define(function(number) {
var e = document.createElement("div"); //...and initialize however.
this.element = e;
e.winControl = this;

this.number = number;
this.symbol = "";
//Also consider using pointerDown event here instead of click; might respond quicker
e.addEventListener("click", this._click.bind(this));
}, {
//Instance members
_click: function (e) {
//Your handler. "this" will be the instance of Cell that was clicked
}
});

this._click函数,如你所见,引用了实例成员Cell._click。调用此函数的绑定(bind)方法是您随后指定要在该方法中用作“this”的确切对象的方式。如果不调用 .bind(this),处理程序仍会被调用,但“this”将是全局上下文,而不是您关心的对象。

关于javascript - 我如何在winjs中的转发器元素中绑定(bind)点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23580156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com