Question

I'm learning BackboneJS using a book called beginning backbone, as far as I understood I can render my own el elements. however when I call the render function it doesn't render anything on the page, when I use console.log(view.el); it outputs what should be rendered so I guess its an issue with the render function.

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 0
    }
}); 

var Library = Backbone.Collection.extend({
    model: Book
});

var View = Backbone.View.extend({
    initialize: function()
    {
        this.render();
    },
    render: function()
    {
        this.$el.html('Hello Library');
        return this;            
    }
});

var book1 = new Book({title: "title1",author:"author1",pages: 11});
var book2 = new Book({title: "title2",author:"author2",pages: 2});

var library = new Library([book1,book2]);

var view = new View({
    model: book1,
    tagName: 'ul',
    className: 'page',
    attributes: {'data-date': new Date()}
});
Était-ce utile?

La solution

Try this: http://jsfiddle.net/tonicboy/nWvRy/

The problem you had is that you specified tagName and className, which will render a detached node. You must then manually attach that node onto some place on the screen for it to appear. The other option (which I have done) is to specify an el attribute for an element already on the screen, then the view will be rendered (attached) to that pre-existing node. You can use el or tagName, className and attributes but not both.

HTML:

<div id="view-wrapper"></div>

JS:

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 0
    }
}); 

var Library = Backbone.Collection.extend({
    model: Book
});

var View = Backbone.View.extend({
    initialize: function()
    {
        this.render();
    },
    render: function()
    {
        this.$el.html('Hello Library');
        return this;            
    }
});

var book1 = new Book({title: "title1",author:"author1",pages: 11});
var book2 = new Book({title: "title2",author:"author2",pages: 2});

var library = new Library([book1,book2]);

var view = new View({
    model: book1,
    el: '#view-wrapper',
    attributes: {'data-date': new Date()}
});

UPDATE:

Here's another version which uses tagName, className and attributes. Notice how the view render() method has to attach it to an existing element.

http://jsfiddle.net/tonicboy/nWvRy/1/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top