Passing parameters into the Backbone events object of a backbone view

Javascriptbackbone.js

Javascript Problem Overview


I have the following events for a Backbone View. Its a product view - with three tabs ("All", "Top 3", "Top 5")

Can I somehow pass a parameter into the method declaration so that it is equivalent to the following (this doesn't work)?

events : {
    "click #top-all":          "topProducts(1)"
    "click #top-three":      "topProducts(2)"
    "click #top-ten":         "topProducts(3)"
},
topProducts(obj){
    // Do stuff based on obj value
}

Javascript Solutions


Solution 1 - Javascript

You could put the extra argument in a data attribute on the clickable item instead; something like this:

<a id="top-all" data-pancakes="1">

And then topProducts can figure it out itself:

topProducts: function(ev) {
    var pancakes = $(ev.currentTarget).data('pancakes');
    // And continue on as though we were called as topProducts(pancakes)
    // ...
}

Solution 2 - Javascript

I generally prefer to do something like this:

events : {
   "click #top-all":    function(){this.topProducts(1);}
   "click #top-three":  function(){this.topProducts(2);}
   "click #top-ten":    function(){this.topProducts(3);}
},
topProducts(obj){
   // Do stuff based on obj value
}

Solution 3 - Javascript

What you can do, is just check the id of the element which is received as currentTarget in arguments.

topProduct: function (e) {
    var id = e.currentTarget.id;
    if (id == "top-all") // Do something
    else if (id == "top-5") // Do something
    else if (id == "top-3") // Do something
}

Solution 4 - Javascript

You can do so using closures:

EventObject.on(event, (function(){
    var arg = data; // Closure preserves this data
    return function(){
        doThis(arg);
    }   
})());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpaddle42380View Question on Stackoverflow
Solution 1 - Javascriptmu is too shortView Answer on Stackoverflow
Solution 2 - JavascriptDreView Answer on Stackoverflow
Solution 3 - JavascriptSachinView Answer on Stackoverflow
Solution 4 - JavascriptYusuf BhabhrawalaView Answer on Stackoverflow