【问题标题】:DurandalJS composition calling Knockout twiceDurandalJS 组合调用 Knockout 两次
【发布时间】:2018-01-03 12:01:40
【问题描述】:

我正在使用带有 Knockout 的 DurandalJS 来加载包含数据的页面。数据是通过 ajax 调用加载的,因此在执行回调之前数据不可用。

发生的情况是,当最终加载数据并调用ko.applyBindings(model) 时,它已经尝试绑定数据一次,并抛出错误,指出数据无法绑定两次。我想阻止 Durandal 这样做,并允许我手动应用绑定。

代码:

define(['plugins/router', 'durandal/app', 'gcharts', 'jquery'], function (router, app, gcharts, $) {

    var projectStatsModel = function (data) {

        this.projectId = data.projectId;
        this.projectName = data.projectName;
        this.projectDescription = data.projectDescription;
        this.projectPlatform = data.projectPlatform;

        this.projectPointsLabel = "Total Points: " + data.projectNumPoints;
        this.projectStoriesLabel = "Total Stories: " + data.projectNumStories;
        this.projectCreatedDateLabel = "Created " + data.projectCreationDate;
        this.projectUpdateDateLabel = "Last Updated " + data.projectModifyDate;

        this.projectEpics = data.projectEpics;
        this.projectStories = data.projectStories;

        return this;
    }

    var ctor = function () {

        function drawPage(data) {
            var model = projectStatsModel(data);
            ko.applyBindings(model);
        }

        function loadData() {

            var projectId = router.activeInstruction().params[0];

            $.ajax({
                url: '/ClubhouseData/GetProjectDetails',
                data: {
                    'projectId': projectId
                },
                type: 'GET',
                cache: 'false',
                success: function (result) {
                    console.log(result);
                    drawPage(result);
                }
            });
        }

        ctor.prototype.activate = function () {
            loadData();
        }
    };


    return ctor;
});

【问题讨论】:

    标签: javascript jquery knockout.js durandal


    【解决方案1】:

    在我应用绑定之前,作为安全预防措施,我总是检查元素是否已经绑定到我的应用程序上。

    if (isBound("container"))
        ko.cleanNode(document.getElementById('container'));
    // Bind
    ko.applyBindings(viewModel, document.getElementById("container"));
    

    我的 isBound 方法:

    var isBound = function (id) {
        if (document.getElementById(id) != null)
            return !!ko.dataFor(document.getElementById(id));
        else
            return false;
    };
    

    这将防止您的错误发生,因为如果已经绑定,它将在应用之前删除绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2021-09-16
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多