javascript - How to extract common methods into a function -


i want extract common method chains prevent copy paste identical code.

how in javascript way ?

original

if(this.get('with_coverage')){   svg.append("text")       .attr("x", (width / 2))       .attr("y", 0 - (margin.top / 2))       .attr("text-anchor", "middle")         .style("font-size", "16px")        .style("text-decoration", "underline")       .text("with coverage"); } else{   svg.append("text")       .attr("x", (width / 2))                    .attr("y", 0 - (margin.top / 2))       .attr("text-anchor", "middle")         .style("font-size", "16px")        .style("text-decoration", "underline")         .text("without coverage"); } 

expected

var apply_style = attr("x", (width / 2))       .attr("y", 0 - (margin.top / 2))       .attr("text-anchor", "middle")         .style("font-size", "16px")        .style("text-decoration", "underline");  if(this.get('with_coverage')){   svg.append("text")       .apply_style()       .text("with coverage"); } else{   svg.append("text")       .apply_style()       .text("without coverage"); } 

svg.append("text")     .attr("x", (width / 2))     .attr("y", 0 - (margin.top / 2))     .attr("text-anchor", "middle")       .style("font-size", "16px")      .style("text-decoration", "underline")     .text("with"+(this.get('with_coverage')?"":"out")+" coverage"); 

magic.


some people don't ternary operators mixed in code. in case can this:

function applystylebasedoncondition(selection, actions, condition, t, f){     actions.call(selection);     (condition ? t : f).call(selection); }  applystylebasedoncondition(svg.append("text"), function(){          .attr({           x: width / 2,           y: 0 - (margin.top / 2),           "text-anchor": "middle"       })        .style({           "font-size": "16px",           "text-decoration": "underline"       }); }, this.get('with_coverage'), function(){      this.text("with coverage"); }, function(){      this.text("without coverage"); }); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -