backbone.js新手系列
我正试图写一些backbone.js的东西,以便更好地了解它在哪里,以及是否适合我的项目。无论如何,我有一个网站,我加载的网页内容集合 Json数据在我的路由器上返回(pid、名称、标题、内容),默认为backbone.js新手系列,backbone.js,Backbone.js,我正试图写一些backbone.js的东西,以便更好地了解它在哪里,以及是否适合我的项目。无论如何,我有一个网站,我加载的网页内容集合 Json数据在我的路由器上返回(pid、名称、标题、内容),默认为 defaultRoute: function (actions) { this.showInfo('food'); }, showInfo: function (id) { var view = new ContentView({ model: this._items.at(id
defaultRoute: function (actions)
{
this.showInfo('food');
},
showInfo: function (id)
{
var view = new ContentView({ model: this._items.at(id) });
$(".active").removeClass("active");
$("#" + id).addClass("active");
view.render();
}
如果我在“新ContentView({model:this.\u items.at(0)})”中用0代替id,我将获得集合中的第一个项,如果我在视图中这样做:
var ContentView = Backbone.View.extend({
el: $('#content'),
render: function ()
{
this.el.empty();
$(this.el).append(this.model.attributes.content);
return this;
}
});
我得到的内容显示完美,但当然可能不是我想要的内容
是否可以根据name==“food”?从集合中进行选择??我不想将内容映射到id号,这会破坏在db中存储的目的
对不起,如果这看起来像一个愚蠢的问题,但我已经爬了整个寻找,我肯定我错过了一些简单的东西
这是我的完整导航路由器代码,以备不时之需
var NavigationRouter = Backbone.Router.extend({
_data: null,
_items: null,
_view: null,
routes: {
"p/:id": "showInfo",
"*actions": "defaultRoute"
},
initialize: function (options)
{
var _this = this;
$.ajax({
url: "page_data.php",
dataType: 'json',
data: {},
async: false,
success: function (data)
{
_this._data = data;
_this._items = new ItemCollection(data);
_this._view.render();
Backbone.history.loadUrl();
}
});
return this;
},
defaultRoute: function (actions)
{
this.showInfo('home');
},
showInfo: function (id)
{
var view = new ContentView({ model: this._items.at(id) });
$(".active").removeClass("active");
$("#l_" + id).parent().addClass("active");
view.render();
}
});
主干将一组函数混合到其内部 因此,如果您想在集合中找到模型,其中
name===“food”
,您可以执行以下操作:
var foodModel = this._items.find(function(model) {
return model.get('name') === 'food';
});
// this will set foodModel to the first model whose name is 'food'
作为补充说明,您不需要在渲染函数中调用empty
,它可以是:
render: function() {
$(this.el).html(this.model.get('content'));
return this;
}
jQuery的
html
函数只是用传入的html字符串替换元素的内容。因此,我必须为每个页面创建一个新的var homeModel等,我将根据内部显示信息进行路由。\导航路由之外的项目将未定义您没有使用下划线的find
功能。您只需在this.\u items
中找到已经存在的模型,并保存对它的引用。然后,您可以对其进行处理,将其传递到现有视图,传递到新视图,等等。