58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Backbone.jsAdvent Calendar 2011

Day 1

動的に作られる要素にイベントをbindする

Last updated at Posted at 2012-03-16

Backbone.js Advent Calendar 1日目!

参加者が増えないと2人で25日回すことになるので,どんどん参加してください:)
http://atnd.org/events/22017
参加方法は,atndで登録したあと,AdventCalendarタグとBackbone.jsタグを付けて投稿してもらえれば,advent calendar用ページに登録します.
http://qiita.com/adcal/backbone

Backbone.jsのイベント登録

Backboneではイベントを

var myView = Backbone.View.extend({
    events: {
        "click .hello-button": "hello"
    },
    hello: function() {
        alert("hello!");
    }
});

のように記述するが,eventsはview作成時にbindされるためこの書き方だと動的に作る要素に対して利用できない.

var myView = Backbone.View.extend({
    initialize: function() {
        $('.hello-button').click(hello);
    },
    hello: function() {
        alert("hello!");
    }
});

のように書くという方法もなくはないが,登録イベント数が増えて来るとひどいことになる…

こういう場合はdelegateEventsを利用する.

var myView = Backbone.View.extend({
    initialize: function() {
        var events = {
            "click .dynamic-hello-button": "hello"
        };
        this.delegateEvents(events);
    },
    hello: function() {
        alert("hello!");
    }
});

のようにinitializeの中でdelegateEventsを利用して登録するといい.

58
55
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?