firebird
firebird

Reputation: 3511

Backbone js: Event not firing issue

How come the event does fire when a button is clicked?

var test1 = new Test({ Name: "Test 1", id: 1 });
var test2 = new Test({ Name: "Test 2", id: 2 });
var test3 = new Test({ Name: "Test 3", id: 3 });
var tests = new TestCollection([test1, test2, test3]);

TestView = Backbone.View.extend({
    initialize: function () {
        this.render();
    },
    events:
    {
        "click .btn": "clickbtn"
    },
    render: function () {
        $("#tests_template").tmpl(tests.toJSON()).appendTo("#tests_list");
        this.delegateEvents();
        return this;
    },
    clickbtn: function () {
        alert('test');
    }
});

var testView = new TestView();

<script id="tests_template" type="text/x-jquery-tmpl">    
    <li> 
    <b>${Name}</b><input type="button" id="btn" value="click" class="btn"/>
    </li> 
</script>

<ul id="tests_list">
</ul>

Upvotes: 0

Views: 846

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72858

the events declaration works with the el element of your view. right now, you have your code directly appending the html output to something other than your view's el.

this will fix it:


TestView = Backbone.View.extend({
    initialize: function () {
        this.el = $("#tests_list");
        this.render();
    },
    events:
    {
        "click .btn": "clickbtn"
    },
    render: function () {
        var html = $("#tests_template").tmpl(tests.toJSON());
        $(this.el).append(html)
        return this;
    },
    clickbtn: function () {
        alert('test');
    }
});

Upvotes: 3

Related Questions