我正在清理我的JS代码,并希望创建名称空间并使用JS OO。我在Object Literal模式上找到了一个非常神tutorial by Rebecca Murphey。
现在我想知道如何使用它来实现例如通过编写jQuery UI自动完成:
// Pseudocode
$('#input_field').myNameSpace.my_search();
var myNameSpace= {
my_search : function() {
$(this).autocomplete({...});
},
my_other_function: function() {}
};
目前我正在使用自己的插件:
$('#input_field').my_search();
(function ($) {
$.fn.my_search = function () {
$(this).autocomplete({
minLength: 2,
source: function( request, response ) {
jQuery.ajax({
url: callback_url,
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( jQuery.map( data, function( item ) {
return {
id: item.id,
value: item.name,
name_encoded: item.name_encoded
}
}));
}
});
},
select: function( event, ui ) {
(...)
}
});
}
})(jQuery);
任何帮助表示感谢。
更新
我的第一个例子非常接近,James Kyburz也非常接近(但工作)。我简化了James的答案,以避免复杂的返回数据。
(function () {
// Namspace which also kind of works like an interface
$.fn.my_name_space = function(opt) {
this.autosuggest_brand = autosuggest.autosuggest_brand;
return this;
}
var autosuggest = {
autosuggest_brand : function(action) {
$(this).autocomplete({
// Autocomplete stuff here
});
},
som_other_function _ function() {}
}
})(jQuery);
答案 0 :(得分:1)
不,你不能为jQuery插件使用命名空间(或者只是非常复杂 - 当你在命名空间对象上执行.my_search()
方法时,选择的context会丢失 )。
您当前的插件很好;如果你想要命名空间,那么使用像namespace_search
这样的前缀。
答案 1 :(得分:1)
我仍在尝试,但不认为这是可能的
一种方法是将一切都包装在一个函数中,而不是命名空间......
$.fn.my_namespace = function() {
var el = this;
var foo = function() { console.log('foo', el); };
var bar = function() { console.log('bar', el); };
return { foo: foo, bar: bar };
}
$('input:first').my_namespace().foo() // foo, [input...]
$('input:first').my_namespace().bar() // bar, [input...]
除非您需要使用defineProperty支持旧浏览器,否则可能是一个解决方案
Object.defineProperty($.fn, 'my_namespace', {
get: function() {
var el = this;
return {
foo: function() { console.log( 'foo', el); },
bar: function() { console.log( 'bar', el); },
}
}
});
$('input:first').my_namespace.foo() // foo, [input...]
$('input:first').my_namespace.bar() // bar, [input...]