简体   繁体   中英

Backbone custom event callback arguments

I'm attempting to pass an argument called newIndex in a custom event from one view to another using the trigger() function. Here's an excerpt from the first view:

var ProductListView = Backbone.View.extend({

    el: '#products',

    events:{
            sortupdate: function(event, ui){
                    ui.item.trigger('moved', ui.item.index());
            }
    }
});

The element on which the 'moved' event is being triggered is another view. Here's an excerpt from that view:

var ProductItemView = Backbone.View.extend({

    events: {
            moved: 'viewMoved'
    },

    initialize: function(){
            _.bindAll(this, 'render', 'viewMoved');
    },

    viewMoved: function(newIndex){
            anotherFunc(this.model, newIndex);
    },

});

The issue I'm having is that in the anotherFunc() call, the newIndex argument appears to be the event itself rather than the value that I passed in when I triggered the event. If I adjust the viewMoved callback to the following, it works correctly:

viewMoved: function(event, newIndex){
    anotherFunc(this.model, newIndex);
},

Is this intended functionality? Is the event itself always the first argument passed to a custom event's callback, or is something else going on here? If it's intended is this documented somewhere? I was unable to find any reference to this in the Backbone documentation.

Backbone uses jQuery heavily under the hood, and your ui.item is actually a jQuery object. See the documentation for the trigger function .

In summary, you're using jQuery's trigger because ui.item is not a Backbone View. Extra parameters are always passed after the event object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM