开发者

Rendering problem

From the backbone documentation:

All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not.

I have following very simple javascript file:

CBBItem = Backbone.Model.extend(
{
});

CBBTrackItem = Backbone.View.extend(
{
    template: _.template("<span><%= title %></span>"),

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

    render: function()
    {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
    }
});

And a html page like this:

 <script type="text/javascript">
 $(function()
 {
    var itm1 = new CBBItem({ title: 'track 1'});
    var itmUI1 = new CBBTrackItem({ model: itm1, id: "kzl" });
    itmUI1.render();
 });
 </script>

<body>
    <div id="kzl"></div>
</body>

My view item doesn't want to render although there is a created div on the page. I can trick the situation in many ways. For example doing something like this

var itm1 = new CBBItem({ title: 'track 1'});
var itmUI1 = new CBBTrackItem({ model: itm1, id: "big_kzl" });
$(itmUI1.render().el).appendTo("#kzl");

But, why is th开发者_C百科e main case not working?


Here's one possibility: you aren't setting the el for the view, so it doesn't know what to do with your template. Could you modify your view-calling code to look like this?

var itmUI1 = new CBBTrackItem({
    model: itm1,
    id: "big_kz1",
    el: "#kz1"
});
itmUT1.render();

Alternatively, you could set the el value within the initialize of the view if the value never varies. The advantage to doing so is that callers of the view don't have to know this information and thus the view is more self-contained.


If the document already has the element you want to use as el for a particular view, you have to manually set that dom element as the el attribute when the view is initialized. Backbone provides you no shortcut for doing that.


I've experienced problems when passing values like ID and events in during construction as opposed to defining them during extension. You may want to check and see if that's the difference you're looking for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜