سؤال

i got this script:

 (function () {
    var app = WinJS.Application;
    WinJS.Namespace.define("Example", {
        randsFunction: WinJS.Binding.as ( {
         //Setting randNum to be returned from an anonymous function every second using setInterval.
            randNum:function(){
                var num = 0; setInterval(
                    function () {
                        num = Math.floor((Math.random() * 100) + 1);
                    }, 1000)
                return num;
            }
        })
    });

    app.onactivated = function () {
// Now this is how we call the Example Namespace trying to replace the contents of the #myDiv (from the default.html) to a new value generated from randsFunction.

        Example.randsFunction.bind('randNum', function (value) {
                var d = document.getElementById('myDiv');
                d.textContent = value;
        })
}

    app.start();

}());

When ran, the content inside the div prints:function () {
var num = 0; setInterval( function () { num = Math.floor((Math.random() * 100) + 1); }, 1000)
return num; }

It seems like WinJS.Binding cannot differentiate between a plain string and/or a function. Or what do you think is the problem? Any suggestion is highly appreciated

هل كانت مفيدة؟

المحلول

WinJS.Binding.as only works against properties to produce an observable proxy.

It looks like you want to update a property on a timer and bind it to the textContent of an element.

You should create the observable proxy:

WinJS.Namespace.define("Example", {
    bindSource: WinJS.Binding.as({
        num: 0 
    })
});

Bind it to your element:

Example.bindSource.bind("num", function (newValue, oldValue) {
    var d = document.getElementById('myDiv');
    d.textContent = newValue;
});

Then update the value through the observable proxy:

setInterval(function () {
    Example.bindSource.num = Math.floor((Math.random() * 100) + 1);
}, 1000);

So your whole example would look something like this:

(function () {
    var app = WinJS.Application;

    WinJS.Namespace.define("Example", {
        bindSource: WinJS.Binding.as({
            num: 0
        })
    });

    app.onactivated = function () {

        Example.bindSource.bind("num", function (newValue, oldValue) {
            var d = document.getElementById('myDiv');
            d.textContent = value;
        });

        setInterval(function () {
            Example.bindSource.num = Math.floor((Math.random() * 100) + 1);
        }, 1000);
    }

    app.start();

}());

Hope that helps and you can see more examples of binding with WinJS at http://try.buildwinjs.com/#binding.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top