Gam*_*mak 3 javascript views backbone.js
所以我对backbone.js很新,而且一般不太擅长JavaScript,所以我想知道是否有人可以向我解释为什么
我无法在我的视图中定义我的EL属性和Template属性,然后在我的渲染中使用this.template.相反,我必须在我的渲染功能中定义模板和el.
var ProductView = Backbone.View.extend({
el: $('#product-list'),
initialize: function() {
this.el.html('<span style="color:white">loading...</span>');
}, // end initialize
render: function(collection) {
// // assign the template
this.template = $('#product_template');
// Where the template will be placed
this.el = $('#product-list');
// Add the collection to the main object
this.collection = collection;
// add tthe data to the html variable
var html = this.template.tmpl(this.collection.toJSON());
// place the html in the element.
this.el.html(html);
// not even sure what the hell this is.
return this;
} // end render
});
Run Code Online (Sandbox Code Playgroud)
你不能这样做:
var ProductView = Backbone.View.extend({
el: $('#product-list'),
// ...
Run Code Online (Sandbox Code Playgroud)
并得到任何有用el的#product-list,甚至不存在,当你的ProductView是建立在DOM可能; 所以试图用$('#product-list')的el仅仅是经典的"我忘了使用$(document).ready()中的骨干打扮"的问题.如果在您定义 ProductView 时存在$('#product-list'),则el应该使用for .#product-list
你可以这样做:
var ProductView = Backbone.View.extend({
el: '#product-list',
// ...
Run Code Online (Sandbox Code Playgroud)
然后说$(this.el)当你需要在视图方法中做事时.不仅是$(this.el)通常的使用方式,el而且它也有效,而且非常重要.
同样的问题适用于#product_template.
看看你的代码我看到了这个:
// INstantiate the view
this.view = new ProductView();
// Bind the view and collection
// So when the collection is reset, the view executes the render method
Products.bind("reset", this.view.render);
Run Code Online (Sandbox Code Playgroud)
据推测,render重置事件会触发.但是,这是一个很大的,但是,该render方法不绑定到合适的this任何地方,所以this不会是ProductView当render被称为并且this不会有任何你希望它; 因此你的奇怪的"未定义"错误.
你可以_.bindAll在你的initialize:
initialize: function() {
_.bindAll(this, 'render');
// ...
Run Code Online (Sandbox Code Playgroud)
但通常你想在创建它时给视图一个集合,并且视图会将自己绑定到事件上,所以你的结构仍然有点奇怪.
您还可以this在致电时提供上下文(AKA )bind:
collection.bind('reset', this.render, this);
Run Code Online (Sandbox Code Playgroud)
这个问题是不是在你定义的方式el或者template,它在你是如何设定的回拨.在Workspace您的路由器中,您正在为集合刷新事件设置回调,如下所示:
// Bind the view and collection
// So when the collection is reset, the view executes the render method
Products.bind("reset", this.view.render);
Run Code Online (Sandbox Code Playgroud)
问题是,您将方法设置为回调,但是您没有提供上下文对象作为绑定的第三个参数 - 因此调用该方法,但this在方法中引用全局对象,而不是视图.所以this.el未定义,因为它根本没有查看视图实例.尝试:
// Bind the view and collection
// So when the collection is reset, the view executes the render method
Products.bind("reset", this.view.render, this.view);
Run Code Online (Sandbox Code Playgroud)
看看会怎么样.
(我做了一个的jsfiddle以证明el和template进行正常的情况下正确设置,但实际上它并不包括上述修复程序,这是很难小样没有服务器端数据:http://jsfiddle.net/nrabinowitz/QjgS9 /)
| 归档时间: |
|
| 查看次数: |
9373 次 |
| 最近记录: |