使用Backbone.js显示Div

时间:2012-02-18 18:51:17

标签: javascript html backbone.js backbone-events

我开始使用Backbone.js和我试图用javascript做简单的事情,这是show / hide divs。我得到显示div但我无法隐藏它,我尝试了很多东西,任何想法?或者可能更复杂?

var Step1View = Backbone.View.extend({
    el: $('body'),
    events: {
        'click #more': 'more',
        'click #hide': 'hide',
    },

    initialize: function (){
        _.bindAll(this, 'render', 'more', 'next', 'less');
        this.render();
    },

    render: function (){
        var self = this;
        $(this.el).append("<a id='more'>Show more</a>");
        $(this.el).append("<div id='show' style='display: none'>Div12</div>");
        return this;
    },

    more: function (){
        $('#more').text('Hide more');
        $('#more').attr('id', '#hide');
        $('#show').show();
    },

    less: function (){
        $('#hide').text('Show more');
        $('#show').hide();
    },

});

干杯

2 个答案:

答案 0 :(得分:5)

你这里有很多问题。

您尝试将事件绑定到不存在的hide方法,您的events应该如下所示:

events: {
    'click #more': 'more',
    'click #hide': 'less',
},

您的initialize方法正在尝试绑定一个不存在的方法next。您的initialize看起来应该更像这样:

initialize: function (){
    _.bindAll(this, 'render', 'more', 'less');
    this.render();
},

您的more方法正在将id设置为#hide,但应该是hide

more: function (){
    $('#more').text('Hide more').attr('id', 'hide');
    $('#show').show();
},

您的less方法无法将id切换回more

less: function (){
    $('#hide').text('Show more').attr('id', 'more');
    $('#show').hide();
}

你在less之后有一个迷路逗号会让一些浏览器不高兴。

演示:http://jsfiddle.net/ambiguous/8HkdT/

交换id这样的属性有点狡猾。您最好使用单独的链接显示和隐藏<div>或只需一个切换按钮,同时显示和隐藏。

答案 1 :(得分:2)

Backbone源代码说:

// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.

您的代码说:el: $('body'),但只需说出el: 'body'

即可

自Backbone 0.9起,您可以使用this.$el代替$(this.el)

http://documentcloud.github.com/backbone/#View-$el

你可能想写'click #hide': 'less'而不是'click #hide': 'hide'