使用backbone.js - this.template.clone();
无效,因为这指的是我认为的每个循环。如何编写它以便引用模板?感谢
model = new Backbone.Model({
data: [
{ text: "site 1", href: "link1.htm" },
{ text: "site 2", href: "link2.htm" },
{ text: "site 3", href: "link3.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },
]
});
var View = Backbone.View.extend({
initialize: function () {
//console.log('initializing ' + this.options.blankOption);
this.template = $('#list-template').children();
},
el: '#container',
events: {
'click button' : 'render'
},
model:model,
render: function(event){
event.preventDefault();
var data = this.model.get('data');
$.each(data,function (i,v) {
//console.log(v.text + " " + v.href);
//var li = this.template.clone().find('a').attr('href', v.href).text(v.t.text);
var li = this.template.clone(); /// this refers to the each loop
});
}
});
//var view = new View({blankOption:"emptySTring"});
var view = new View({});
答案 0 :(得分:1)
使用其他变量引用您想要的this
:
var that = this;
$.each(data,function(i, v) {
var li = that.template.clone();
});
答案 1 :(得分:0)
使用自定义变量在this
函数中保存对render
的引用:
...
render: function(event){
var self = this;
event.preventDefault();
var data = this.model.get('data');
$.each(data,function (i,v) {
//console.log(v.text + " " + v.href);
//var li = this.template.clone().find('a').attr('href', v.href).text(v.t.text);
var li = self.template.clone(); /// this refers to the each loop
});
}
...
了解JS的范围如何运作。