define([
'jquery',
'underscore',
'backbone',
'text!modules/index/templates/container.html'
], function($, _, Backbone, container_temp){
var indexView = Backbone.View.extend({
el: $('.main_container'),
initialize:function(){
_.bindAll(this, 'render');
},
render:function(){
var $this = this;
var $el = this.el;
$.get('/js/index/render', {}, function(data){
var dat = JSON.parse(data);
$this.pars = dat;
var tpl = _.template(container_temp, dat);
$el.html(tpl);
});
}
});
return new indexView;
});
運行此代碼應該用HTML填充$ el。但是,我的瀏覽器在$el.html(tpl);
處出現混亂。爲什麼我的「el」不能在Backbone中工作?
Uncaught TypeError: Object #<HTMLDivElement> has no method 'html'
爲了解決這個問題,我必須這樣做:$($el).html(tpl);
讓jQuery的寄存器。
這看起來很尷尬。在我過去的項目中,我一直以前的方式完成它,並且一直都很成功。
在'GET'回調,只要使用'$此$ el'和刪除本地'$。 el' =>'$ this。$ el.html(tpl)'。你已經通過在'$ this'變量中捕獲它來創建'this'的閉包,所以你可以直接使用它(因爲你不會多次使用它,它不會節省任何時間)。 – WiredPrairie 2013-02-18 14:14:55