Backbone Js - 无法触发按钮点击事件

时间:2014-08-23 13:44:45

标签: jquery html backbone.js backbone-events

我正在学习骨干js,因为我试图编写一个示例应用程序,我试图在文本框的列表中添加数据。

JSFiddle链接提供了代码 - http://jsfiddle.net/ynkJE/2662/

参考代码:

<!DOCTYPE html>
<html>  
<head>
<title></title>
</head>
<body>
<!--html-->
<div id="mainDiv">
    <div id="headerDiv">
        <input id="txtName" type="text" />
        <input id="btnEnter" type="button" value="Enter" />
    </div>
    <div id="gridDiv">
        <ul id="grdlist">
        </ul>
    </div>
</div>
<!--templates-->
<script type="text/template" id="grid-template">
    <%_.each(items, function(item){ %>
    <li>
        <label id="lblName"><%=item.name %>></label>
        <input type="button" id="btnEdit" value="Edit">
        <input type="button" id="btnDelete" value="Delete">
    </li>
    <%}); %>
</script>
<script type="text/template" id="item-template">
<li>
        <label id="lblName"><%= name %></label>
        <input type="submit" id="btnEdit" value="Edit">
        <input type="button" id="btnDelete" value="Delete">
</li>
</script>
<!--Javascript-->
<script src="JsLibs/jquery-2.1.1.js" type="text/javascript"></script>
<!--    <script src="JsLibs/json2.js" type="text/javascript"></script>-->
<script src="JsLibs/underscore.js" type="text/javascript"></script>
<script src="JsLibs/backbone.js" type="text/javascript"></script>
<script type="text/javascript">
    var App = {};

    App.NameModel = Backbone.Model.extend({
        defaults: {
            name: 'Ravi'
        }
    });

    App.NameList = Backbone.Collection.extend({
        model: App.NameModel
    });

    App.ListView = Backbone.View.extend({
        //tagName: 'li',
        el: '#gridDiv',
        initialize: function () {
            _.bindAll(this, 'render','editName');
        },
        render: function () {
            var template1 = $("#item-template").html();
            console.log(this.model.toJSON());
            this.$el.append(_.template(template1, this.model.toJSON()));
            return this;
        },
        events: {
            'click btnEdit': 'editName',
            'click btnDelete': 'deleteName'
        },
        editName: function (e) {
            //e.preventDefault();
            alert('edit');
        },
        deleteName: function () {
            alert('delete');
        }
    });

    var enterView = Backbone.View.extend({
        el: 'headerDiv'
    });

    $(document).ready(function () {
        $('#btnEnter').click(function () {
            var myModel = new App.NameModel({ name: $('#txtName').val() });
            var myView = new App.ListView({ model: myModel });
            //$('#gridDiv').append(myView.render().el);
            myView.render();
        });
    });


</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

选择器错误,您缺少ID选择器的#

events: {
    'click #btnEdit': 'editName',
    'click #btnDelete': 'deleteName'
},

另请注意,ID必须是唯一的,您应该使用类。