3

我使用 jquery.load 函数动态加载页面,但加载的页面未绑定到 viewModel?

应用程序.js

function viewModel(){
    var self = this;
    self.users = ko.observable();

    Sammy(function() {
        this.get("#/users",function() {
            $.get("/api/users",function(data){
                self.users(data);
            });
            $("#content").load("pages/users.html");
        });
    }).run("#/");
}

ko.applyBindings(new viewModel());

索引.html:

<html>
    <body>
        <div id="content"></div>
        <script src="statics/js/lib/jquery-1.8.2.js"></script>
        <script src="statics/js/lib/knockout-2.2.0.debug.js"></script>
        <script src="statics/js/lib/knockout.mapping.js"></script>
        <script src="statics/js/lib/sammy.js"></script>
        <script src="statics/js/lib/app.js"></script>
    </body>
</html>

页面/users.html

<ul data-bind="foreach: users">
    <li><span data-bind="text: fullName"></span></li>
</ul>
4

2 回答 2

11
$("#content").load("/pages/users.html", function () {
   ko.applyBindings(new viewModel());
}

应该这样做...

于 2012-11-06T14:59:41.450 回答
-1

我解决了动态页面加载后重新应用绑定的问题

function viewModel(){
    var self = this;
    self.users = ko.observable();

    Sammy(function() {
        this.get("#/users",function() {
            $.get("/api/users",function(data){
                self.users(data);
            });
            $("#content").load("pages/users.html", null, function (response, status, xhr) {
                if (status != "error") {
                } 
                    ko.applyBindings(self, $(".dynamic-page-content").get(0)); 
                }
            });
        });
    }).run("#/");
}

ko.applyBindings(new viewModel());
于 2012-11-06T15:01:46.257 回答