javascript:durandaljs,在viewmodel中的applyBindings

时间:2013-04-03 13:56:21

标签: javascript knockout.js durandal

我正在尝试使用durandaljs制作包含动态内容的单页应用程序。例如,如果更改设置中的语言,则会更新UI。我正在使用SignalR从服务器加载对象,除了我导航时,一切正常。第一次加载视图时,我收到以下错误:

Uncaught Error: Unable to parse bindings.
Message: ReferenceError: router is not defined;
Bindings value: compose: { 
        model: router.activeItem, //wiring the router
        afterCompose: router.afterCompose, //wiring the router
        transition:'entrance', //use the 'entrance' transition when switching views
        cacheViews:true //telling composition to keep views in the dom, and reuse them (only a good idea with singleton view models)
        }

但如果我重新加载页面,则视图会正确显示。 以下是viewmodel的示例:

define(function (require) {
    var p = require('hubs/myhub'),
        rep = require('repositories/myrepository');
    var myViewModel = function(data, proxy, cookie) {
        var self = this;
        self.proxy = proxy;
        self.cookie = cookie;
        self.Labels = ko.observableArray([]);
        try {
            self.proxy
                .invoke('Setup', self.cookie.Username, self.cookie.Language)
                .done(function (res) {
                    if (res.Result) {
                        console.log(JSON.stringify(res.Object, null, 4));
                        self.Labels(res.Object.Labels);
                    } else {
                        console.log(res.Error);
                    }
                });
        } catch (e) {
            console.log(e.message);
        }
    };
    return {
        activate: function () {
            var cookie = JSON.parse($.cookie(rep.cookieName));
            ko.applyBindings(myViewModel({}, p.proxy, cookie), document.getElementById('my_container'));
        }
    };
});

如果我取消激活功能的applyBinding,则导航中不再存在问题。有没有正确的方法来做到这一点?

我修改了以下的return语句:

return {
        myModel: new myViewModel ({ }, p.proxy, JSON.parse($.cookie(rep.cookieName))),
        activate: function () {
            this.myModel.init();
        }
    };

并将signalr调用包装在init()函数中。一切都很好。

1 个答案:

答案 0 :(得分:2)

这是正确的方法! DUrandal为你调用Ko.applybindings;)意味着Durandal有约束力!

Hot Towel SPA Durandal Knockout and Dynatree