0

使用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({});
4

2 回答 2

1

使用另一个变量引用this您想要的:

var that = this;

$.each(data,function(i, v) {
    var li = that.template.clone();
});
于 2013-02-25T09:36:59.670 回答
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 的作用域是如何工作的。

于 2013-02-25T09:37:36.797 回答