Search code examples
javascripthtmlcssbackbone.jsunderscore.js

Dynamic HTML rendering using backbone js not replacing the original content after click event


I am learning backbone js and recently came across an issue with dynamic html rendering. I have two tabs and as I click on each tab, the html below must change. Im unable to change the html. I gave an if/else condition in the html code based on backbone js model. I think I have to call render function, Am I right?

Is there any other way to do it?Also, my find function is iterating and printing hello 5,6 times based on the array. But isn't it supposed to find only the state object? Thanks in advance.

tab1 tab2 <% _.find(tab1, function(item){ if(item.state != "active") {%> hello <% }else{ hi <% } }) %>


Solution

  • You can bind a change event to your model to take care of calling the render function each time.

    Ie.

    this.model.bind("change:tab", this.render);
    

    Also, the find function in your example is just being used as a each loop as you are not returning a match, so without seeing the data going in it is difficult to see the cause of your issue.

    You need to return the condition to use the _.each function correctly.

    For example

    var activeTab = _.find(tabs, function(item){ return item.state === "active"; });
    

    A more suitable underscore method for this would be findWhere, which will work like

    var activeTab = _.findWhere(tabs, { state : "active"});