如何在winjs中绑定转发器元素中的click事件?

时间:2014-05-10 10:55:08

标签: javascript windows windows-phone-8 winjs

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

    <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";
    })
});

但是如何将click事件绑定到某个函数,以便我可以从该函数中访问底层的单元格对象?

2 个答案:

答案 0 :(得分:3)

使用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。调用此函数的绑定方法就是如何指定要使用的确切对象&#34;这个&#34;在那个方法里面。如果没有.bind(this)的调用,仍然会调用处理程序,但是&#34;这个&#34;将是全球背景,而不是你关心的对象。

答案 1 :(得分:0)

抱歉,我从未让你的解决方案运行,但我 我发现了另一种在转发器中绑定点击的方法。我将发布我的样本进行导航

<ul data-win-control="WinJS.UI.Repeater" data-win-bind="winControl.data: navigations">
    <li data-win-control="Navigation.NavigationItem" data-win-bind="winControl.data: this">
        <span data-win-bind="textContent: Name; className: Selected;"></span>
        <span data-win-bind="textContent: Selected;"></span>
    </li>
</ul>

正如您所看到的,我创建了一个非常简单的控件,并使用“data-win-bind =”winControl.data绑定了转发器项:这个“。”

命名空间如下所示:

WinJS.Namespace.define("Navigation", {
    dataBinding: WinJS.Binding.as({
        navigations: new WinJS.Binding.List([]),
    }),

    NavigationItem: WinJS.Class.define(
            function (element, options) {
                this.element = element;
                this.element.onclick = function (event) {                        
                    var item = this.winControl.data;
                    // Handle your onclick here
                    // for example: 
                    item.clickHandler();
                };
            }
        ),
});

并添加如下项目:

Navigation.dataBinding.navigations.push(WinJS.Binding.as({
    Name: "Home",
    Page: "/pages/home/home.html",
    // more... for example:
    clickHandler: function() {
       // Do Something
    };
}));