2013-02-25 27 views
0

的每個循環 - this.template.clone();不起作用,因爲這指的是我認爲的每個循環。我如何編寫它以便引用模板?感謝這是指使用backbone.js使用主幹

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

爲什麼不在每個循環的外面引用'var that = this;' – pfried 2013-02-25 09:36:34

回答

1

參考您要使用另一個變量的this

var that = this; 

$.each(data,function(i, v) { 
    var li = that.template.clone(); 
}); 
0

使用自定義變量來保存你的render函數內部參考this

... 
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的範圍界定的工作。