And*_*rle 4 javascript closures backbone.js underscore.js
我有一个骨干视图,可以在下划线模板中呈现搜索结果.由于我想在结果中突出显示搜索词,我在模板中有以下打印方法:
print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')
Run Code Online (Sandbox Code Playgroud)
它按预期工作,但我必须searchTerm在全局命名空间中设置变量才能使其工作.我想知道是否有办法在print方法中访问我的视图模型,所以我可以像这样写:
print(someKey.replace(searchTerm, '<b>' + this.model.get('searchTerm') + '</b>')
Run Code Online (Sandbox Code Playgroud)
或者,如果我可以在我的渲染函数中将searchTerm设置为局部变量并在我的模板中访问它.
这是整个Backbone视图:
var searchTerm;
var SearchResultView = Backbone.View.extend({
initialize: function() {
this.model.bind('change:rows', this.render, this);
this.model.bind('change:searchTerm', this.clear, this)
},
template: _.template("<tr><td><% print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')); %></td></tr>", this),
render: function() {
searchTerm = this.model.get('searchTerm')
_.each(this.model.get('rows'), function(row) {
this.el.append($(this.template(row.doc)));
}, this)
},
clear: function(){
this.el.empty();
}
});
Run Code Online (Sandbox Code Playgroud)
小智 8
我不确定我完全理解你的问题.但我沿着这些方向做了一些事情,将多个对象传递给我的模板函数.
$(this.el).html(_.template(html)($.extend({}, this.model.toJSON(), App.lists.toJSON())))
Run Code Online (Sandbox Code Playgroud)
jquery扩展函数允许我将两个对象合并为一个.因此,在您的情况下,您可以在模板期间将"searchTerm"与模型合并.
_.template(html)($.extend({}, row.doc, {"searchTerm": searchTerm}))
Run Code Online (Sandbox Code Playgroud)
您的另一个选择是将整个模型传递到模板函数中,并在模板中执行下划线迭代.如果您需要更多解释,请告诉我.
编辑:
这是jquery扩展的链接
如果你不使用jquery ,下划线也有和扩展方法
编辑编辑:
这只是为了给你一个我的第二个建议的例子.可能需要一些调整才能投入你的,但这是个主意.
template: _.template("
<% _(rows).each(function(row) { %>
<tr><td><% print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')); %></td></tr>
<% } %>
"),
render: function(){
this.el.append(this.template(this.model.toJSON()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12899 次 |
| 最近记录: |