开发者

backbone.js app odd behavior with views

trying to wrap my head around backbone.js and so far I like what I'm seeing. I have a question about views that I'm not quite understanding. I'm creating a demo app that uses a form input to append a LI to a UL. Pretend it's a list of movies. So I have:

  • AppView, the view for my entire application
  • MovieView, a single LI in the UL of movies

When you click to add a movie, I want to create a new MovieView and append it to the UL in my AppView. I've got a fiddle here: http://jsfiddle.net/nCEz2/

What's happening is that instead of appending an LI to the UL, each time I create a new MovieView, the old MovieView is updated. So instead of appending a new LI开发者_StackOverflow社区 to the UL each time, I only ever have the first one I added, updated to the newest item I've added. Any ideas why I'm only getting one MovieView and it's not appending like I think it should?


Your example isn't working the way you expect because the $el property of MovieView is initialised once so it always represents the same DOM object in all instances of MovieView. So although you change the text of the li each time you render a new MovieView you are always adding the same li to the ul and after the first time you add it thats a no-op.

One way to get the behaviour you are expecting is to use the tagName property so that backbone will automatically create a new li element for each view instance. e.g.

var MovieView = Backbone.View.extend({
    tagName: 'li',

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

        return this.render();
    },

    render: function () {
        $(this.el).text(this.model.get('name'));
    }
});

Then in you AppView.movieAdded method:

movieAdded: function (newMovie) {
    var movieView = new MovieView({
        model: newMovie
    });

    $('#movieList').append(movieView.el); 
},
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜