javascriptjquerybackbone.jsbackbone-events

Draggabilly.js events in the Backbone.js view


I am using Draggabilly.js inside a Backbone view as follows:

var appView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
     var draggie = new Draggabilly(this.el);
     draggie.on('dragEnd', this.updateModel); //This works by I can access the this.model
    },
    events: {
      'dragEnd':'updateModel' //This doesn't work
    },
    updateModel: function(instance, event, pointer){
      //Here I want to update my model bassed on the pointer's x and y
      //However I can't access this.model
    }
)};

Draggabilly provides and event 'dragEnd' for when the draginng is over. However I can integrate this in my Backbone view as an event.

Can you please advice?


Solution

  • In order to access to the View context you can do:

    draggie.on('dragEnd', _.bind( this.updateModel, this ));
    

    But, if you want to remove the listener of dragEnd later it might be useful to use bindAll in your initialize code:

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

    Check the Backbone documentation for further info.