【问题标题】:Events not working when using Mustache with Backbone.js将 Mustache 与 Backbone.js 一起使用时事件不起作用
【发布时间】:2012-06-19 07:45:20
【问题描述】:

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

这是我的代码:

ItemView.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>

【问题讨论】:

  • 我认为当您单击按钮时它会发布/提交。这是按钮的默认设置。尝试添加 type="button" 并告诉我会发生什么。
  • 不行 :-( 我将按钮元素更改为 ,但仍然没有事件

标签: events view backbone.js mustache


【解决方案1】:

您将在 render 中替换视图的 el

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

当您这样做时,您将丢失附加到 this.el 的 jQuery delegate,该 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;这将在this.el 中为您提供&lt;li&gt;,因为您已将视图的tagName 设置为li

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

this.setElement(rendering);

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

【讨论】:

  • 发现,使用setElement后,事件触发正确。我猜文档对 el 和 setElement 有点混乱。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
相关资源
最近更新 更多