Sammy.js : 部分 calling/rendering 我的 html 两次

Sammy.js : Partial calling/rendering my html twice

我是 Knockout 和 sammy 的新手。我正在使用 Sammy(路由器)和 KnockOut(绑定)实现 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);
            });
        });

当我检查控制台时它说 "You cannot apply bindings multiple times to the same element.(…)".

我是不是做错了什么?

Partial 和 Render 有什么区别?

我猜你正在将新的 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;
};

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

感谢您的回复和评论。问题出在 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 });
        });

它工作得很好。再次感谢。