【问题标题】:Sammy.js : Partial calling/rendering my html twiceSammy.js:部分调用/渲染我的 html 两次
【发布时间】:2016-02-24 13:44:57
【问题描述】:

我是淘汰赛和萨米的新手。我正在使用 Sammy(router) 和 KnockOut(binding) 实现 SPA。

我有以下代码。

this.get('#/Page/:operation', function (context) {
            this.partial('templates/Page1.html', { cache: false }).then(function (content) {
                // the first argument to then is the content of the
                // prev operation
                $('#sammyDiv').html(content);
            });
        });

当我检查控制台时,它显示 “您不能多次将绑定应用到同一个元素。(...)”

我在这里做错了吗?

Partial 和 Render 有什么区别?

【问题讨论】:

  • 这看起来很麻烦。 Knockout 不仅仅是“绑定”,它是一个通过模型控制整个 DOM 的系统。如果您在模型之外进行 DOM 操作,您将遇到问题。我建议你看看使用 Knockout 组件的 Sammy 路线。您没有在此处显示您调用 ko.applyBindings 的位置,但这就是生成您收到的错误消息的原因。

标签: html knockout.js sammy.js


【解决方案1】:

我猜你正在将新的 html 注入到已经绑定的父级中。您也应该更具体地确定要绑定的 div。 I.E 将绑定应用到您注入的 html 的父 div,或者清理并重新应用绑定。我在整个应用程序中都使用这两种方法。

if (isBound("my-div"))
    ko.cleanNode(document.getElementById('my-div'));
ko.applyBindings(myModel, document.getElementById('my-div'));

辅助功能:

// Checks if Element has Already been Bound (Stops Errors Occuring if already bound as element can't be bound multiple times)
var isBound = function (id) {
    if (document.getElementById(id) != null)
        return !!ko.dataFor(document.getElementById(id));
    else
        return false;
};

我在所有绑定之前使用此检查作为安全网。

【讨论】:

    【解决方案2】:

    感谢您的回复和 cmets。问题出在 Sammy 路由器上。

    this.get('#/Page/:operation', function (context) {
                this.partial('templates/Page1.html', { cache: false }).then(function (content) {
                    // the first argument to then is the content of the
                    // prev operation
                    $('#sammyDiv').html(content);
                });
            });
    

    改为

    this.get('#/Page/:operation', function (context) {
                this.partial('templates/Page1.html', { cache: false });
            });
    

    它工作得非常好。再次感谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多