jQuery、underscore.js、backbone.jsのbindメソッドについて


backbone.jsのサンプルコードを読んでいると、bindという名前のメソッドがよく使われてます。

そして、bindという名前のメソッドはbackbone.jsにも、underscore.jsにも、jQueryにも定義されています。

慣れている人は問題ないのでしょうが、私は読んでいて混乱したので、それぞれの定義と、サンプルで使い方をまとめておきたいと思います。

backbone.jsのbindメソッド

   object.bind(event, callback, [context])

レシーバオブジェクトの'change'や'destroy'などのイベントに、コールバックを紐付けます。
第3引数にcontextを渡すことによって、callback実行時の「this」を設定できます。


jQueryのbindメソッド

   .bind( eventType [, eventData] , handler(eventObject) )

要素が持つ、例えば”click”などのDOMイベントに対してコールバック関数を紐付けます。
eventDataはコールバック関数に渡されます。

underscore.jsのbindメソッド

    _.bind(function, object, [*arguments]) 

functionを実行する「関数」を返します。
functionで参照される「this」にはobjectが使われます。
argumentsを渡すと、functionに渡す引数をあらかじめ指定しておくことができます。(カリー化)

backbone.jsで使うときの使用例

backbone.jsのexampleにあるtodosのBackbone.Viewの例です。

    window.TodoView = Backbone.View.extend({

	//... is a list tag.
	tagName:  "li",

	// Cache the template function for a single item.
	template: _.template($('#item-template').html()),

	// The DOM events specific to an item.
	events: {
	    "click .check"              : "toggleDone",
	    "dblclick div.todo-text"    : "edit",
	    "click span.todo-destroy"   : "clear",
	    "keypress .todo-input"      : "updateOnEnter"
	},

	// The TodoView listens for changes to its model, re-rendering.
	initialize: function() {
	    this.model.bind('change', this.render, this);
	    this.model.bind('destroy', this.remove, this);
	},

	// Re-render the contents of the todo item.
	render: function() {
	    $(this.el).html(this.template(this.model.toJSON()));
	    this.setText();
	    return this;
	},

	// To avoid XSS (not that it would be harmful in this particular app),
	// we use `jQuery.text` to set the contents of the todo item.
	setText: function() {
	    var text = this.model.get('text');
	    this.$('.todo-text').text(text);
	    this.input = this.$('.todo-input');
	    this.input.bind('blur', _.bind(this.close, this)).val(text);
	},


initializeで、backbone.jsのbindを使用してます。

Viewが保持しているmodelに'change'イベントが発生したときにrenderを、'destroy'イベントが発生したときにremoveをコールするように紐付けています。

    initialize: function() {
        this.model.bind('change', this.render, this);
        this.model.bind('destroy', this.remove, this);
    },


またrenderから呼ばれるsetTextの内部でbindが使われてます。

    this.input = this.$('.todo-input');
    this.input.bind('blur', _.bind(this.close, this)).val(text);

1つ目のbindはjQueryのbindです。.todo_inputにblurイベントに、コールバック関数を紐付けてます。
紐付けているコールバック関数は、underscore.jsのbindの戻り値です。
underscore.jsのbindはclose関数をthisのコンテキストで呼ぶ関数を作成していて、これがjQueryのbindに渡されています。