1

我已经检查了这篇文章这篇文章、这篇文章以及许多其他文章,但似乎没有一个解决方案对我有帮助。我要做的就是用一个html数组替换视图的内容。数组中的每个元素都是使用下划线模板引擎创建的。这是我的代码:

模板:

    <script type="text/template" id="radioItemTemplate">
        <li>
            <div class="button price <% if(enabled){%>enabled<%}%>">$<%=price%></div>
            <div class="title name"><%=name%></div>
        </li>
    </script>

Javascript:

iHateThisView = Backbone.View.extend({
    template: _.template($("#radioItemTemplate").html()),

    events:{
        "click .price": "_onRadioItemClick"
    },

    radioItems: null,
    radioItem: null,

    initialize: function (options) {
        this.radioItems = options.radioItems;
        this.radioItem = options.radioItem;
    },

    render: function () {
        trace("rendering");
        var radioItems = this.radioItems.first(3);
        var activeRadioItem = this.radioItem.get('name');
        var result = [];
        var scope = this;
        _.forEach(radioItems, function (radioItem) {
            var option = {
                name: radioItem.get('name'),
                price: radioItem.get('price'),
                enabled: activeRadioItem == radioItem.get('name')
            };
            result.push(scope.template(option));
        });

        //THE TRICKY ZONE -START

        this.$el.html(result);

        //THE TRICKY ZONE -END
        return this;
    },

    _onRadioItemClick: function (event) {
        $el = this.$el;
        var clickedName = $el.find('price');
        console.log('clickedName');
    }
});

除了用 a 包装我的 html 之外,<div>这正是我在第一次渲染时想要的。但是,如果我再次调用我的渲染函数,则所有事件都不起作用。所以根据我所有的阅读,我认为this.delegateEvents()应该修复事件的丢失,所以我尝试了这个:

//THE TRICKY ZONE -START

this.$el.html(result);
this.delegateEvents();

//THE TRICKY ZONE -END

据我所知,这什么也没做。在第一次渲染时,当我单击 radioItems 时,我会得到我的console.log,但在重新渲染之后再次没有

所以然后我读到我可能必须这样做:

//THE TRICKY ZONE -START

this.$el.html(result);
this.delegateEvents(this.events);

//THE TRICKY ZONE -END

这也什么也没做。

于是我尝试了另一种方法:

//THE TRICKY ZONE -START

this.setElement(result);
this.delegateEvents();   //with and without this line

//THE TRICKY ZONE -END

添加了数组中的第一项,即使在第一次渲染时事件也不起作用。

请恢复我的理智伙计们,我没有别的办法了。

4

0 回答 0