Search code examples
htmlbackbone.jsbackbone-viewsbackbone-events

How to pass diff parameters dynamically for a function using backbone js?


Here is the fiddle i was playing with

fiddle

this is my html

<div id="search_container">a</div>
<script type="text/template" id="search_template">
    <label>Search</label>
    <input type="text" id="search_input" />
    <input type="button" class="button" id="search_button" value="Search" />
     <input type="button" class="button" id="a" value="asfasd" />
     <input type="button" class="button" id="b" value="Seaasdasdrch" />
     <input type="button" class="button" id="c" value="Seadasdasdasrch" />
</script>

and this is my Javascript

 SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), {} );
        // Load the compiled HTML into the Backbone "el"
        this.$el.html( template );
    },
    events: {
        "click input[class=button]": "doSearch"  
    },
    doSearch: function( event ){
        // Button clicked, you can access the element that was clicked with event.currentTarget
       alert( "Search for " + $("#a").val() );
    }
});
    
var search_view = new SearchView({ el: $("#search_container") });

I want to call a same function for a bunch of buttons, but I want to give different parameters for them depending upon their values. It takes the value of first element as value; how do I overcome and give unique attribute to different buttons?

Please help me out .. !


Solution

  • If I get your question properly, I think you want to capture the different values of the following buttons

    <input type="button" class="button" id="search_button" value="Search" />
    <input type="button" class="button" id="a" value="asfasd" />
    <input type="button" class="button" id="b" value="Seaasdasdrch" />
    <input type="button" class="button" id="c" value="Seadasdasdasrch" />
    

    If so, you can modify your code to the following:

    doSearch: function( event ){
        // Button clicked, you can access the element that was clicked with event.currentTarget
        alert( "Search for " + $(event.currentTarget).attr('value') );
    }