Javascript usage in Windows Store App

Piotr Rachwał

I'm struggling with Metro-style app. This is basic scenario: After pressing a button on main screen you jump to another page. Then I create part of html content dynamically. For example:

<img id="bbb" src="/images/1.jpg">
<img id="ccc" src="/images/2.jpg">
<img id="ddd" src="/images/3.jpg">

And after that I want attach JS function to "click" event of each img tag that I added. So I do something like that:

(function () {
"use strict";
WinJS.UI.Pages.define("/pages/myPage/myPage.html", {
    ready: function (element, options) {
        element.querySelector("#bbb").onclick = this.button1Click("ff");
        element.querySelector("#ccc").onclick = this.button1Click("ee");
        element.querySelector("#ddd").onclick = this.button1Click("dd");
    },
    button1Click : function (arg)
    {
        console.log(arg);
    }
});

})();

Of course part:

element.querySelector("#bbb").onclick = this.button1Click("ff");

is in loop.

But after this kind of attachment functions execute once after load (even without click) and disappear. I checked it in debug mode and right after load onclick property of each element had null value. Using this method:

element.querySelector("#bbb").addEventListener("click", this.button1Click("ff"), false);

and another combinations like

document.getElementById("bbb").addEventListener("click", this.button1Click("ff"), false);

etc. gives same result. I appreciate any help.

Bavell

I believe you need to remove the parens for your onClick functions, as this will immediately invoke the function (as you have observed)

From this:

ready: function (element, options) {
    element.querySelector("#bbb").onclick = this.button1Click("ff");
    element.querySelector("#ccc").onclick = this.button1Click("ee");
    element.querySelector("#ddd").onclick = this.button1Click("dd");
},

To this:

ready: function (element, options) {
    element.querySelector("#bbb").onclick = this.button1Click;
    element.querySelector("#ccc").onclick = this.button1Click;
    element.querySelector("#ddd").onclick = this.button1Click;
},

Then you would need to get the args into your click function, perhaps binding it to the html itself. There may be a way to bind the function args at the same time, but I'm not so familiar with WinJS.

HTML

<img id="bbb" src="/images/1.jpg" data-arg="ff">

JS

function button1Click() {
    // Get the clicked element
    // JQuery solution
    var arg = $(this).data('arg');
    console.log(arg)
}

In addition, you could simplify things a bit and use classes instead of ID's for your HTML and assign the onClick handler once.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related