0

我正在使用 jsView (v1.0.0-alpha)

我在从视图中获取数据时遇到问题。让我有以下代码。(我在这里创建了一个简化版本http://jsfiddle.net/j5oc0svg/)我试图通过使用占位符名称来获取我之前绑定到视图的数据对象。它总是返回'undertified'。如果我调用 $.view().views 那么我可以看到我之前绑定的视图和数据。

如何使用占位符或(视图名称?)获取绑定到视图的数据?

提前致谢。

<!DOCTYPE html>        
<html>
<head>
  <script src="http://code.jquery.com/jquery.js"></script>
  <base href="http://www.jsviews.com/samples/"/>
  <link href="samples.css" rel="stylesheet"/>
  <script src="../download/jsviews.js"></script>
</head>
<body>

<table><tbody id="peopleList"></tbody></table>

<script id="personTmpl" type="text/x-jsrender">
  <tr>
    <td>Name</td>
    <td>{{:name}}</td>
  </tr>
</script>

<script>

           $.ajax({
                url: "http://localhost:4728/api/People/,
                dataType: 'json'
            }).done(function (data) {
                if (data!= null) {
                    var template = $.templates("#personTmpl");
                    template.link("#peopleList", data);
                }
            }).fail(function (exception) {
                console.log(exception.message);
            });


           // Let's say this code is in button on click or push subscriber 
           hub_proxy.client.UpdateSomething = function (someArgs) {
                  var data = $.view('#peopleList').data; //underfined.
           }

</script>

</body>
</html>
4

2 回答 2

2

Yes, the answer from raina77ow is a good answer.

A couple more ways of getting to specific data, e.g. for this case where you are looking to obtain the array you passed in to link() in the first place:

// Get the nearest ancestor view for an array, and hence the data
var arr = $.view('#peopleList tr').get("array").data;

// Get the top-level view created by the link view or render call (In this case, this is the "array" view)
var arr = $.view('#peopleList tr').get().data;

// Get the top-level data that was passed to the link or render method (In this case, also the array)
var arr = $.view('#peopleList tr').ctx.root;

I forked raina77ow's demo here and added those alternatives: http://jsfiddle.net/BorisMoore/p9mfmb3r/

BTW looking at the unit tests can also be a good source of ideas:

https://github.com/BorisMoore/jsviews/tree/master/test/unit-tests

于 2014-09-07T17:26:05.157 回答
1

您似乎错过了Views在 jsView 中是(某种)组合的事实:换句话说,每个 View 对象可能包含一组内部视图,等等。

随着$.view(selector)您检索包含该selector元素的最外层视图。因为#peopleList,它只是其他 View 的容器,没有自己的数据。在这种情况下,您可能会寻找仍然#peopleList在范围内的最内部视图:这是通过将inner参数设置为$.view()to 来完成的true

console.log( $.view('#peopleList', true) ); // Array of Objects

或者,您可以只为每一行查找一个特定的数据对象:

console.log( $.view('#peopleList tr:eq(0)').data ); // Object {name: "Adriana"} 
console.log( $.view('#peopleList tr:eq(1)').data ); // Object {name: "Robert"}

演示。我在:eq这里使用选择器只是为了说明;但是您始终可以为视图分配名称,然后在选择器中引用它。

于 2014-09-07T16:08:39.660 回答