Search code examples
javascriptjqueryhtmlbackbone.jsunderscore.js

How to Add Dynamically added anchor tag to the underscore template


I am creating a template, there is an anchor tag which is dynamically creating. I need to add this to my underscore template.

And also in the below method setIconClass, I am returning the class, but once setIconClass method is executed, the class is empty, i need that class to be appended to my anchor tag

This is what I have tried:

HTML:

<div id="section">
 <div class="container abc"></div>
 <div class="container def"></div>
</div>

JS:

define(['underscore', 'backbone'], function(_, Backbone) { 
   var View = Backbone.View.extend({ 
     el: "#section",
     initialize: function() {
       this.render();
     },
render: function() {
            var that = this;
            var _container = "", _linkURL = "", _targetWindow="",_domain="", _class="";
            _container = $('.container');
            if(_container.length > 0){
                $(_container).each(function(){
                    _targetWindow = $(this).attr('window');
                    _domain = $(this).attr('dom');
                    _linkURL = _domain + $(this).attr('url');
                    that.setIconClass($(this),_class);
                    $(this).wrapInner('<a class="'+_class+'" href="'+_linkURL+'" target="'+_targetWindow+'"></a>');
                });
            }
        },
setIconClass : function(checkClass,_class){
            var _dClass = (checkClass) ? checkClass.attr('class').toLowerCase() : "";
            if(_dClass.indexOf('abc') > 0){
                _class="abc";
                return _class;
            }
            else if(_dClass.indexOf('def') > 0){
                _class="def";
                return _class;
            }
        }
   });


});

Solution

  • You need to assign _class equal to the return value of setIconClass. Javascript is pass by value.

    _class = that.setIconClass($(this),_class);