keep context within BackboneJS view

2019-08-06 13:09发布

问题:

Is there a shorter more elegant way to keep context within BackboneJS view?

    this.$el.find(this.itemViewContainer).sortable("destroy").sortable({
        connectWith:'.tasks',
        delay:140,
        revert:200,
        items:'li:not(.locked)',
        placeholder:'ui-state-highlight',
        start:_.bind(function (event, ui){this._sortStart(event, ui);}, this),
        receive:_.bind(function (event, ui){this._sortReceive(event, ui);}, this),
        stop:_.bind(function (event, ui){this._sortStop(event, ui);}, this)
    });

I am reffering to the:

  • start event
  • receive even
  • stop event

it is important that: this, event and ui will be passed to the inner view event.

回答1:

You can use _.bindAll to lock this to the view in your callbacks:

bindAll _.bindAll(object, [*methodNames])
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the object's function properties will be bound to it.

and you could use it like this

var V = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, '_sortStart', '_sortReceive', '_sortStop');

        this.$el.sortable("destroy").sortable({
            items: 'li:not(.locked)',
            start: this._sortStart,
            receive: this._sortReceive,
            stop:this._sortStop
        });
    },

    _sortStart: function(event, ui) {
    },
    _sortReceive: function(event, ui) {
    },
    _sortStop: function(event, ui) {
    }
});

http://jsfiddle.net/nikoshr/wAAZ5/