我尝试使用来自以下位置的Backbone样板实现BackGrid: https://github.com/azat-co/super-simple-backbone-starter-kit
1.使用以下代码处理名为GridHandler.js的文件:
var Territory = Backbone.Model.extend({});
var Territories = Backbone.Collection.extend({
model: Territory,
url: "data/territories.json"
});
var territories = new Territories();
var columns = [{
name: "id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "name",
label: "Name",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
}, {
name: "pop",
label: "Population",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "percentage",
label: "% of World Population",
cell: "number" // A cell type for floating point value, defaults to have a precision 2 decimal numbers
}, {
name: "date",
label: "Date",
cell: "date"
}, {
name: "url",
label: "URL",
cell: "uri" // Renders the value in an HTML anchor element
}];
2.grid.html文件包含ID为' example-1-result'的DIV。
3.在app.js中创建了一个View视图如下:
require(['libs/text!header.html', 'libs/text!home.html', 'libs/text!grid.html', 'libs/text!footer.html', 'js/GridHandler'],
function (headerTpl, homeTpl, gridTpl, footerTpl, gridHandler) {
// Other Views here.
GridView = Backbone.View.extend({
el: "#content",
template: gridTpl,
initialize: function() {
// Initialize a new Grid instance
var grid = new Backgrid.Grid({
columns: columns,
collection: territories
});
// Render the grid and attach the root to your HTML document
$("#example-1-result").append(grid.render().el);
// Fetch some countries from the url
territories.fetch({reset: true});
},
render: function() {
$(this.el).html(_.template(this.template));
}
});
app = new ApplicationRouter();
Backbone.history.start();
});
即使带有DIV标签的grid.html'示例1-result'网格也未显示。模板内容已分配到内容区域。
grid.render()。el - >正确生成网格表。
为什么网格没有显示在#content中 - > #example-1-result?
'#示例-1-结果'是在模板文件中,这是问题吗?
另一种方式的问题:
我们如何将一些数据分配给View中模板中的DIV?
答案 0 :(得分:0)
在您看来,您有:
$("#example-1-result").append(grid.render().el);
Jqueries在DOM中查找ID为example-1-result
的元素。如果你的模板还没有插入到DOM中(我认为不是这样),jquery将无法找到你的元素,因此将它附加到伟大的虚空中,而不是你的元素......
尝试将视图中的该行更改为:
this.$el.append(_.template(this.template));
this.$el.find("#example-1-result").append(grid.render().el)