playing with subscribe ko v3rc

ko.examRTChart debug sample

by jwstott

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.0.0rc.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<div>
    <div id="chart" data-bind="examRTChart: exams, colWidth: '8', height:40, width:250"></div>
</div>

CSS

.chart rect {
     fill: steelblue;
     stroke: white;
 }

 .correct {
     fill: salmon !important;
 }

JavaScript

ko.bindingHandlers.examRTChart = {
    init: function (element, valueAccessor, all, vm, context) {
        console.time('init')
        var obsvArray = valueAccessor(),
            data = ko.unwrap(obsvArray),
            $elem = $(element),
            options = ko.unwrap(all()),
            height = options.height || $elem.height,
            width = options.width || $elem.width(),
            colWidth = parseInt(options.colWidth, 10) || 20, // def to 20px wide bar-columns
            xScale,
            yScale,
            chart;
        /*
      Construct two scales, based on our knowledge of the dataset and the desired chart size. 
      To fix the maximum bar size to 80×20, construct two linear scales:
      */
        xScale = d3.scale.linear()
            .domain([0, 1])
            .range([0, colWidth]);
        yScale = d3.scale.linear()
            .domain([0, 1])
            .rangeRound([0, height]);
        
        makeChart();

        obsvArray.subscribe(function (changes) {
            changes.forEach(function (change) {
                if (change.status === 'added') {
                    printMe(change);
                    console.log(change);
                    chart.select("rect:nth-of-type(1)")
                       // .data([change.value])
                       // .attr('class', 'correct') // can do , but subsiquent class would need !important
                        .transition()
                        .duration(400)
                    //.attr('class', 'correct'); // no transistion
                       .style('fill', 'salmon'); //  nice transistion

                }
            });
        }, null, "arrayChange");

        function makeChart() {
            // With the scales ready, construct the SVG container for the chart:
            chart = d3.select(element).append("svg")
                .attr("class", "chart")
                .attr("width", colWidth * data.length - 1) // width * data.length - 1
            .attr("height",...