2

im starting to use Backbone.js and im trying to do somthing simple with javascript, which is show/hide divs. I get to show the div but i cannot hide it, i try many things, any idea? or could be it more sophisticated?

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();
    },

});

Cheers

2 Answers 2

5

You have a lot of problems here.

You're trying to bind an event to a non-existent hide method, your events should look like this:

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

Your initialize method is trying to bind a method, next, which does not exist. Your initialize should look more like this:

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

Your more method is setting the id to #hide but it should be hide:

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

Your less method doesn't switch the id back to more:

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

And you have a stray comma after less which will make some browsers unhappy.

Demo: http://jsfiddle.net/ambiguous/8HkdT/

Swapping the id attributes like that is a bit dodgy. You'd be better off with separate links that you show and hide along with the <div> or just a single toggle button that does both the showing and hiding.

0
2

Backbone source code says:

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

Your code says: el: $('body'), but it's enough to say el: 'body'

And since Backbone 0.9, you can use this.$el instead of $(this.el):

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

And you probably wanted to write 'click #hide': 'less' instead of 'click #hide': 'hide'.

1
  • Thanks for the comments, ill use the new notation, and u are right, better less than hide... :). Cheers.
    – ki0
    Feb 19, 2012 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.