2

我的任务是在 ruby​​ on rails 中做 knockout.js。我想以表格格式列出我的数据库值。我的索引页面是

<%= javascript_include_tag "knockout-2.2.0", "knockout.simpleGrid.1.3" %>

<style type='text/css'> 
    .ko-grid { margin-bottom: 1em; width: 25em; border: 1px solid silver; background-color:White; }
    .ko-grid th { text-align:left; background-color: Black; color:White; }
    .ko-grid td, th { padding: 0.4em; }
    .ko-grid tr:nth-child(odd) { background-color: #DDD; }
    .ko-grid-pageLinks { margin-bottom: 1em; }
    .ko-grid-pageLinks a { padding: 0.5em; }
    .ko-grid-pageLinks a.selected { background-color: Black; color: White; }
    .liveExample { height:20em; overflow:auto } /* Mobile Safari reflows pages slowly, so fix the height to avoid the need for reflows */
</style>
<% @users.each do |user| %>
<script type="text/javascript">
 $(document).ready(function() {

    var initialData = [
     {name:<%= @user_names.to_json.html_safe%>, place: <%= @user_places.to_json.html_safe%> }
    ];

var PagedGridModel = function(items) {
    this.items = ko.observableArray(items);

    this.addItem = function() {
        this.items.push({ name: "New item", place: "dfgd"});
    };

    this.sortByName = function() {
        this.items.sort(function(a, b) {
            return a.name < b.name ? -1 : 1;
        });
    };

    this.jumpToFirstPage = function() {
        this.gridViewModel.currentPageIndex(0);
    };

    this.gridViewModel = new ko.simpleGrid.viewModel({
        data: this.items,
        columns: [
            { headerText: "Name", rowText: "name" },
            { headerText: "Place", rowText: "place" }

        ],
        pageSize: 4
    });
};

ko.applyBindings(new PagedGridModel(initialData));
    });
 </script>
 <%end%>
<div data-bind='simpleGrid: gridViewModel'> <br/></div>

<button data-bind='click: addItem'>
    Add item
</button>

<button data-bind='click: sortByName'>
    Sort by name
</button>

<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
    Jump to first page
</button> 

运行时的结果是

Name                          Place
Nithin,Vipin,Jetson     Vatakara,Calicut,Aluva

所有名称都排成一行,与地点的情况相同。我该如何解决?

4

1 回答 1

2

代替这个

 var initialData = [
     {name:<%= @user_names.to_json.html_safe%>, place: <%= @user_places.to_json.html_safe%> }
    ];

尝试通过迭代一一给出user_name。

我不知道。请你试试这个。

 $(document).ready(function() {
var initialData = new Array;
<% @users.each do |user| %>
initialData.push({name: "<%= user.name %>" , place: "<%= user.place %>" }) ;
<% end %>   
于 2013-01-14T08:37:30.220 回答