Summary Value Calculation with JsViews

心不动则不痛 提交于 2019-12-13 02:57:09

问题


I like to display two summary data on my page by using jsviews binding. The UI will be something like in screenshots.

The user can add/remove the person from the list and it will affect the value of "No. Of People" and the user can edit integer value in textbox and the total values will be shown in "Total Amount."

Yes. I managed to make it work .. Please see my code there. http://jsfiddle.net/michaelsync/eqhkzv3t/3/

But I think it's very ugly esp: this code below.

function observeAmounts(){    
  people.forEach(function (person){
    $.observe(person, 'amount', function(e) {
        var amount =0;
        people.forEach(function(person){
            amount += parseInt(person.amount);
        });
        $('#output2').html('Total Amount: ' + amount);
    });
   });
}

 observeAmounts();

$.observe(people, function(e) {
    var l = $.map(people, function(n, i) { return i; }).length;
    $('#output1').html('Total No. of People: ' + l);
     observeAmounts();
});

Well, I am still reading up the tutorials and the source code/test of jsviews. but I am pretty much news to JsViews. In my current code, I keep on looping up the array to calculate the total amount and the count of people. I think that I might be able to register a helper class but still have to loop the 'people' array to calculate the value.

So, I believe that there might be a better way in JsViews. As JsViews site refers us to post the questions here and the author of JsViews are also here, I decided to post it here to get an advance on doing those summary data. (Yes, you can also view my test code here http://jsfiddle.net/michaelsync/eqhkzv3t/3/ )

Any advice would be appreciated. Thanks!


回答1:


I created an updated version of your jsfiddle here: http://jsfiddle.net/BorisMoore/wch601L9/

The main thing you missed that will help is to use observeAll:

http://www.jsviews.com/#observeAll

$.observable(people).observeAll(totalAmount);

I also added a couple of different approaches for other things:

Declarative event bindings:

<td><button data-link="{on ~remove}">Remove</button></td>

Top-level data-linking to show the length of the array:

<span id="getLength" data-link="length"></span>

and

$("#getLength").link(true, people);

(See also this sample: http://www.jsviews.com/#samples/editable/toplevel-for, for top-level data-linking)



来源:https://stackoverflow.com/questions/25721180/summary-value-calculation-with-jsviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!