保持BackboneJS视图中的上下文 [英] keep context within BackboneJS view

查看:131
本文介绍了保持BackboneJS视图中的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个较短的更优雅的方式来保持BackboneJS视图中的背景?

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)
    });

我reffering的:

I am reffering to the:


  • 启动事件

  • 接受甚至

  • 停止事件

,重要的是:此,事件和用户界面将被传递到内视图事件

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

推荐答案

您可以使用 _.bindAll 以在此回调锁定到视图:

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

bindAll _.bindAll(对象,[*方法名])结果
  结合在运行的数目的对象的方法,通过方法名指定
  每当他们被调用该对象的上下文。非常方便的
  绑定将要用作事件处理程序,功能,这
  否则将有相当无用这个调用。如果不
  提供方法名,所有对象的功能属性将
  绑定到它。

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.

,你可以使用它像这样

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/

这篇关于保持BackboneJS视图中的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆