KnockoutJs: my computed function is not dynamicall

2019-08-23 20:04发布

问题:

I have an application that retrieves a list of users in my database in a paginated way. The first page shows the first 6 users, and when i click the next page in my pagination i get the next 6 users. I get the first list of 6 users, but the problem is after retrieving the next 6 and applying the binding, it doesn't change on the View, and i am sure it retrieves the next 6 because i console logged it. this is the code

this.get("#/search/query::username", function (context) {

        var searchKeyWord = this.params['username'];


        $.ajax({
            url: "http://localhost:8080/dashboard/search/" + this.params['username'] + "/0",
            type: 'GET',
            contentType:'application/json',
            dataType: 'json',
            success: function(data) {
                context.app.swap('');
                context.load('partials/search.html')
                    .appendTo(context.$element())
                    .then(function (content) {

                        console.log(data);
                        ko.applyBindings(searchModel(data),document.getElementById('search'));
                        initCard();
                        genericFunctions();

                        $('.searchPage').twbsPagination({
                            totalPages: data.totalPages,
                            visiblePages: 5,
                            onPageClick: function (event, page) {

                                $.get("http://localhost:8080/dashboard/search/" + searchKeyWord + "/" + (page - 1), function(data, status){


              searchModel(data);

                                });
                            }
                        });
                    });
            }
        });

    });

this is the searchmodel :

function searchModel(data) {

var SearchResult = ko.mapping.fromJS(data);

SearchResult.groupedUsers = ko.computed(function() {

    var rows = [];

    SearchResult.content().forEach(function(user, i) {
        // whenever i = 0, 3, 6 etc, we need to initialize the inner array
        if (i % 3 == 0)
            rows[i/3] = [];

        rows[Math.floor(i/3)][i % 3] = user;
    });

    console.log(rows);

    return rows;
});



return SearchResult;

}

this is the html :

 <div id="users-tab" class="tab-pane fade in active" data-bind="foreach: groupedUsers">

                      <ul class="search-results files row" data-bind="foreach: $data">

                        <li class="search-result form-group col-sm-4 ">
                          <div class="media cover ">
                            <a href="#" class="pull-left">
                              <img alt="" src="assets/images/ici-avatar.jpg" class="media-object img-circle">
                            </a>
                            <div class="media-body">
                              <h4><a href="#" data-bind="text: userName">Ing. Imrich Kamarel</a></h4>
                              <small>First name: <span data-bind="text: firstName"></span></small><br>
                              <small>Last name: <span data-bind="text: lastName"></span></small><br>
                            </div>
                          </div>
                        </li>

                      </ul>


                    </div>
                    <!-- / Tab panes -->

                    <nav aria-label="Page navigation">
                      <ul class="searchPage" id="pagination"></ul>
                    </nav>

回答1:

I don't really have a solution for you but here is how I would approach this situation:

Pseudo-code viewmodel incoming:

var searchViewModel = function(){
    var self = this;
    self.usersOnScreen = ko.observableArray();

    function exampleAjaxCall(){
        $.ajax({
        type: "GET",
        url: 'yourcontroller/youraction',
        contentType: "application/json",
        success: function (data) {
             //add data to self.usersOnScreen() using mapping or in a loop
             }    
        });
    }
    self.pagination = function(){
    // place another ajax call here which handles the paging and map the response to self.usersOnScreen();
    }
    self.init = function(){
    // place your ajax call here and map the response to self.usersOnScreen() 
    }
}

Pseudo-html and js incoming:

<html>
<body>
    <ul data-bind="foreach: usersOnPage">
        <li>
        //Your user data here
        </li>
    </ul>
<script type="text/javascript">
//insert ref to your viewmodel
var vm = new SearchViewModel();
vm.init();
ko.applyBinding(vm);
</script>
</body>
</html>

This way you won't need a computed and I think the code reads 'easier'. I hope this helped you a bit.



标签: knockout.js