Search code examples
javascriptjquery-templatesjsrenderjsviews

Getting the data object by using view name or place holder name


I am using jsView (v1.0.0-alpha)

I am having an issue in getting the data from the view. Let's I have the following code. (I created a simplified version here http://jsfiddle.net/j5oc0svg/ ) I am trying to get the data object that I bind to the view earlier by using the place holder name. It's always return 'undertified'. If I called $.view().views then I can see the view and the data that I bind earlier.

How can I get the data that bind to the view by using the placeholder or (view name?)?

Thanks in advance.

<!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>

Solution

  • You seem to miss the fact that Views in jsView are (sort of) Composites: in other words, each View object may contain set of internal Views, among other things.

    With $.view(selector) you retrieve the outer-most View that contains the selector element. For #peopleList, it's just an container for other Views, with no own data. What you probably look for in this case is finding the inner-most View still having #peopleList in the scope: that's done with setting inner param of $.view() to true:

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

    Alternatively, you can just go for a specific data object for each row:

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

    Demo. I've used :eq selector here just for illustration; but you can always assign a name to a view, then refer to it in the selector.