locked
Calling ViewModel Functions with Declarative Binding RRS feed

  • Question

  • I've used this post on Metro Declarative Data Binding (http://stephenwalther.com/archive/2012/02/26/metro-declarative-data-binding.aspx) as inspiration to build some samples I'm working on.

    Since the RC, though functions in my viewmodel aren't called when I do declarative binding. IOW this simple scenario doesn't work:

    (function () {
        "use strict";
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
        WinJS.strictProcessing();
        var _viewModel = {
            "ViewModel": WinJS.Binding.as({
                "message": "test message",
                changeMessage: function () {
                    Application.Home.ViewModel.message = document.querySelector("#message-box").value;
                }
            })
        };
        WinJS.Namespace.define("Application.Home", _viewModel);
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                args.setPromise(WinJS.UI.processAll().then(function () {
                    WinJS.Binding.processAll(null, _viewModel);
                }));
            }
        };
        app.start();
    })();
    <body data-win-bindsource="Application.Home.ViewModel">
        <input type="text" id="message-box" data-win-bind="value: message; keyup: changeMessage" />
        <div data-win-bind="innerText: message"></div>
    </body>

    This worked in the preview, but doesn't now in the RC. Any ideas on what I need to change?


    • Edited by Craig Shoemaker Sunday, June 24, 2012 12:44 PM fixed code error from pasting
    Saturday, June 23, 2012 2:49 PM

Answers

  • I figured it out. I needed to add "on" to the event name. So instead of keyup it needs to be onkeyup:

    <body data-win-bindsource="Application.Home.ViewModel">
        <input type="text" id="message-box" data-win-bind="value: message; onkeyup: changeMessage" />
        <div data-win-bind="innerText: message"></div>
    </body>

    and in the JavaScript I'm binding the viewmodel by using the public namespace. So instead of using _viewModel directly I am using Application.Home.ViewModel when calling WinJS.Binding.processAll():

    (function () { "use strict"; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; WinJS.strictProcessing(); var _viewModel = { "ViewModel": WinJS.Binding.as({ "message": "test message", changeMessage: function () { Application.Home.ViewModel.message = document.querySelector("#message-box").value; } }) };

    WinJS.Namespace.define("Application.Home", _viewModel);

    app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { args.setPromise(WinJS.UI.processAll().then(function () { WinJS.Binding.processAll(null, Application.Home.ViewModel); })); } }; app.start(); })();


    Sunday, June 24, 2012 12:52 PM