在主干网中使用模板+jquery ui



我有一个主干视图。视图的render如下所示:

render: function()
{
    var template = _.template($("#mytemp").html() , {
        'mylabel' : "test"
    });
    this.$el.html(template);
    this.$el.css({"border" : "1px solid black"})
    this.$el.resizable({ });           
}

问题是,可调整大小的插件通过向$el添加DOM元素来工作。然而,如果我使用$el.html(template),它似乎会清除这些DOM元素,无论我是将其放在可调整大小之前还是之后。第一次调用render时一切正常,但如果再次调用render,则resizable将停止工作。

我需要以某种方式修改我的模板吗?

http://jsbin.com/oyutey/2/edit

问题是,当你这样做时:

this.$el.html(template);

resizable的所有额外DOM元素都会被杀死;然后绑定小部件:

this.$el.resizable({ });

但是resizable仍然认为它被正确绑定,所以第二个CCD_ 6调用什么都不做。结果是,您已经绑定到this.$el,但其DOM元素(如调整大小句柄(已不存在。

一个简单的修复方法是在调用this.$el.html()之前分离可调整大小的,然后在调用之后重新绑定,类似于以下内容:

render: function() {
    var template = _.template($("#mytemp").html() , {
        'mylabel' : "test"
    });
    if(this.rendered) // Unbind the resizable if we've already bound it
        this.$el.resizable('destroy');
    this.$el.html(template);
    this.$el.css({"border" : "1px solid black"});
    this.$el.resizable({ }); // Set up the resizable as usual.
    this.rendered = true;    // Make a note that we've already been here.
    return this;             // This is conventional so it is a good idea to do it.
}

演示:http://jsbin.com/oyutey/3/edit

最新更新