Ben*_*jen 12 javascript jquery-ui backbone.js
我正在学习Backbone.js.我目前假设如果使用Backbone.js,那么所有客户端javascript/jQuery都应该与Backbone集成.从各种在线教程中,我可以看到Backbone如何工作并理解其基本原理.
但是像jQuery UI小部件这样的东西呢?这些也应该与Backbone.js集成吗?例如,我想在表单字段上使用jQuery UI Autocomplete小部件(请参阅下面的代码).我将如何使用Backbone.js进行此操作(或者不使用Backbone进行此类操作)?似乎Backbone的"模型"和"收集"不能与jQuery自动完成小部件一起使用,因为这种东西被绑定在jQuery UI Widget本身中.
(function($){
$(document).ready(function() {
$(this.el).autocomplete({
source: function(req, res) {
$.ajax({
url: '/orgs.json?terms=' + encodeURIComponent(req.term),
type: 'GET',
success: function(data) {
res(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Something went wrong in the client side javascript.');
},
dataType: 'json',
cache: false
});
}
});
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这类事情的标准做法是什么?我唯一能想到的是创建一个视图,然后在渲染功能中添加小部件.但这对我来说似乎并不是非常的主干.
在我看来,使用this.collection@saniko 访问包含数据的集合,我在视图的render功能中设置了自动完成:
render : function() {
...
var me = this; //Small context issues
this.$el.find('input.autocompleteSearch').autocomplete({
source : function(request, response){
me.collection.on('reset', function(eventname){
var data = me.collection.pluck('name');
response(data); //Please do something more interesting here!
});
me.collection.url = '/myresource/search/' + request.term;
me.collection.fetch();
}
});
...
},
...
Run Code Online (Sandbox Code Playgroud)
渲染视图时附加所有插件:
你可以这样做:
render: function () {
var view = this;
// Fetch the template, render it to the View element and call done.
application_namespace.fetchTemplate(this.template, function (tmpl) {
var viewModel = view.model.toJSON();
view.$el.html(tmpl(viewModel));
view.$("#categories").autocomplete({
minLength: 1,
source: function (request, response) {
$.getJSON("url" + view.storeId, {
term: request.term,
}, function (data) {
response($.map(data, function (item) {
return {
value: item.title,
obj: item
};
}));
});
},
select: function (event, ui) {
//your select code here
var x = ui.item.obj;
var categories = view.model.get("x");
// bla bla
}
error: function (event, ui) {
//your error code here
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助