1

所以我正在使用 RequireJs、Mustache 和 Backbone.js 制作一个测试应用程序。我在使用 Mustache 模板渲染模型集合方面取得了一些成功。但是我的 Mustache 模板有一个按钮,当我尝试在视图中的按钮上绑定单击事件时,按钮单击不会调用回调函数。我真的被卡住了,有人能告诉我我哪里做得不对吗?

这是我的代码:

项目视图.js:

define(['jquery', 'backbone', 'underscore', 'mustache', '../../atm/model/item'], function ($, Backbone, _, Mustache, Item) {

var ItemView = Backbone.View.extend({        
    initialize: function() {
    },

    tagName: 'li',

    events: {
        'click .button': 'showPriceChange'
    },

    render: function() {
        var template = $('#template-atm').html();
        var itemObj = this.model.toJSON();
        itemObj['cid'] = this.model.cid;

        var rendering = Mustache.to_html(template, itemObj);
        this.el = rendering;

        return this;
    },

    showPriceChange: function(event) {
        alert('Changing...');
        $('#' + elemId).empty();
        $('#' + elemId).append(document.createTextNode('Changed'));
    },       
});

return ItemView;
});

atm.html:

<!DOCTYPE html>
<html>
<head>
    <title>Elevator</title>
    <script data-main="scripts/main" src="scripts/require-jquery.js"></script>
    <style type="text/css">

    </style>
</head>

<body>
    <h1>Vending Machine</h1>
    <div id="atm-items">
    </div>

    <script id="template-atm" type="html/template">
        <li>
            <p>Item: {{name}}</p>
            <label for="price-{{cid}}">Price:</label>
            <input id="price-{{cid}}" type="text" value="{{price}}"/>
            <button class="button">Change</button>
            <p id="status-{{name}}-{{cid}}">- -</p>
        </li>
    </script>
</body>
</html>
4

1 回答 1

4

您正在替换视图的el内部render

render: function() {
    //...
    this.el = rendering;
    //...
}

当您这样做时,您将丢失delegate附加到的 jQuery this.el,该delegate处理程序(由 Backbone 添加)负责事件路由。

通常,您内容添加到this.el而不是替换 this.el. 如果您的模板如下所示:

<script id="template-atm" type="html/template">
     <p>Item: {{name}}</p>
     <label for="price-{{cid}}">Price:</label>
     <input id="price-{{cid}}" type="text" value="{{price}}"/>
     <button class="button">Change</button>
     <p id="status-{{name}}-{{cid}}">- -</p>
 </script>

那么你会this.$el.append(rendering)在你看来render; 由于您已将视图设置<li>为.this.eltagNameli

或者,如果您确实需要将 保留<li>在模板中,您可以使用setElement替换this.el,this.$el并处理事件委托:

this.setElement(rendering);

大概您将所有这些<li>s 包装在<ul>,<ol><menu>其他地方;如果不是,那么您将生成无效的 HTML,并且浏览器可能会尝试为您更正它,这些更正可能会在其他地方给您带来麻烦,因为您的 HTML 结构可能不是您的选择器认为的那样。

于 2012-06-19T19:39:48.350 回答